from tronapi import Tron from tronapi import HttpProvider full_node = HttpProvider('https://api.trongrid.io') solidity_node = HttpProvider('https://api.trongrid.io') event_server = HttpProvider('https://api.trongrid.io') tron = Tron(full_node, solidity_node, event_server) tron.toSun(1) # result: 1000000 tron.fromSun(1000000) # result: 1
def execute(self, bot, update, args): if self.is_automix(update): sql = self.get_resource("select_automix.sql", plugin="automix") res = self.execute_sql(sql, update.effective_user.id, plugin="automix") if not res["success"] or not res["data"]: msg = f"{emo.ERROR} Automix stopped. No data for user ID {update.effective_user.id}." self.if_automix_then_stop(update, msg) update.message.reply_text(msg) return auto_chars = res["data"][0][1] auto_amount = str(res["data"][0][2]) args = [auto_chars, auto_amount] if len(args) != 2: update.message.reply_text(self.get_usage(), parse_mode=ParseMode.MARKDOWN) return choice = "".join(self.remove_unwanted(args[0].lower())) # Check if user provided any valid characters if len(choice) == 0: msg = f"{emo.ERROR} No valid characters provided. Allowed are: `{self._VALID_CHARS}`" self.if_automix_then_stop(update, msg) update.message.reply_text(msg, parse_mode=ParseMode.MARKDOWN) return amount = args[1] try: amount = float(amount) except: msg = f"{emo.ERROR} Provide a valid TRX amount" update.message.reply_text(msg) return preset = self.config.get("preset") if not str(len(choice)) in preset: msg = f"{emo.ERROR} Betting on {len(choice)} characters not possible - {preset}" self.if_automix_then_stop(update, msg) update.message.reply_text(self.get_usage(), parse_mode=ParseMode.MARKDOWN) return preset = preset[str(len(choice))] # Check if preset configuration has all needed values if "min_trx" not in preset or "max_trx" not in preset or "leverage" not in preset: msg = f"{emo.ERROR} Wrong configuration in preset: {preset}" self.if_automix_then_stop(update, msg) update.message.reply_text(msg) logging.error(msg) self.notify(msg) return # Generate new betting address tron = Tron() account = tron.create_account tron.private_key = account.private_key tron.default_address = account.address.base58 addr = account.address.base58 # Check if generated address is valid if not bool(tron.isAddress(account.address.hex)): msg = f"{emo.ERROR} Generated wallet is not valid" update.message.reply_text(msg) return generated = { "pubkey": account.public_key, "privkey": account.private_key, "addr_hex": account.address.hex, "addr_base58": account.address.base58 } logging.info(f"{addr} TRX address created {generated} - {update}") # Save generated address to database sql = self.get_resource("insert_address.sql") self.execute_sql(sql, account.address.base58, account.private_key) leverage = preset["leverage"] # Save bet details to database sql = self.get_resource("insert_bet.sql") self.execute_sql(sql, account.address.base58, choice, update.effective_user.id) # Get min and max amounts for this bet from config min_trx = preset["min_trx"] max_trx = preset["max_trx"] # Get users wallet to send bet TRX from sql = self.get_global_resource("select_address.sql") res = self.execute_global_sql(sql, update.effective_user.id) # Load message for user betting_msg = self.get_resource("betting.md") betting_msg = betting_msg.replace("{{choice}}", choice) betting_msg = betting_msg.replace("{{factor}}", str(leverage)) betting_msg = betting_msg.replace("{{chars}}", str(len(choice))) if self.is_automix(update): msg = betting_msg.replace( "{{state}}", f"{emo.WAIT} AUTO-MIX: Sending TRX from your wallet...") else: msg = betting_msg.replace( "{{state}}", f"{emo.WAIT} Sending TRX from your wallet...") # Send betting message to user message = update.message.reply_text(msg, parse_mode=ParseMode.MARKDOWN) msg = msg.replace("\n", " ") logging.info(f"{addr} {msg}") manual_mode = False # User has a bot generated wallet if res["success"] and res["data"]: logging.info(f"{addr} Wallet for auto-send: {res['data']}") # Users existing wallet used for auto-send from_user = Tron() from_user.private_key = res["data"][0][2] from_user.default_address = res["data"][0][1] # Get balance (in "Sun") of users wallet address balance = from_user.trx.get_balance() trx_balance = from_user.fromSun(balance) logging.info( f"{addr} TRX Balance - Current: {trx_balance} - Needed: {amount + con.TRX_FEE}" ) # Not enough balance for auto-send if trx_balance < (amount + con.TRX_FEE): # Bet is an auto-bet if self.is_automix(update): msg = f"{emo.ERROR} Automix stopped. Not enough balance." self.if_automix_then_stop(update, f"{addr} {msg}") update.message.reply_text(msg) return # Bet is a manually started bet else: logging.warning( f"{addr} Couldn't auto-send. Not enough balance.") manual_mode = True # Enough balance for auto-send else: try: # Send bet amount from user wallet to generated wallet send = from_user.trx.send(tron.default_address.hex, amount) # Transaction didn't went through if "code" in send and "message" in send: if self.is_automix(update): msg = f"{emo.ERROR} Automix stopped. Can't send {amount} TRX: {send['message']}" self.if_automix_then_stop(update, f"{addr} {msg}") update.message.reply_text(msg) return else: logging.warning( f"{addr} Couldn't auto-send: {send}") manual_mode = True else: if self.is_automix(update): msg = f"{emo.DONE} AUTO-MIX: Successfully sent `{amount}` TRX to `{addr}`" else: msg = f"{emo.DONE} Successfully sent `{amount}` TRX to `{addr}`" logging.info(f"{addr} {msg} - {send}") betting_msg = betting_msg.replace("{{state}}", msg) message.edit_text(betting_msg, parse_mode=ParseMode.MARKDOWN) except Exception as e: if self.is_automix(update): msg = f"{emo.ERROR} Automix stopped. Can't send {amount} TRX: {e}" self.if_automix_then_stop(update, f"{addr} {msg}") update.message.reply_text(msg) return else: logging.warning(f"{addr} Couldn't auto-send: {e}") manual_mode = True # User doesn't have a bot generated wallet else: # Bet is an auto-bet if self.is_automix(update): msg = f"{emo.ERROR} Automix stopped. Generate a wallet first with /start" self.if_automix_then_stop(update, f"{addr} {msg}") update.message.reply_text(msg) return else: logging.warning( f"{addr} Couldn't auto-send: User doesn't have a wallet") manual_mode = True if manual_mode: msg = "*Wallet balance not sufficient*. " msg += f"Send between *{min_trx}* and *{max_trx}* TRX to following address:\n\n`{addr}`" betting_msg = betting_msg.replace("{{state}}", msg) message.edit_text(betting_msg, parse_mode=ParseMode.MARKDOWN) betting_msg = betting_msg.replace("\n", " ") logging.info(f"{addr} {betting_msg}") # --- General logic --- first = self.config.get("check_start") check = self.config.get("balance_check") context = { "tron": tron, "choice": choice, "preset": preset, "update": update, "start": time.time(), "message": message, "sc_trx": 0, # Second chance TRX value "sc_win": False # Second chance won or not } self.repeat_job(self.scan_balance, check, first=first, context=context) logging.info(f"{addr} Initiated repeating job")
event_server=event_server) tron.private_key = 'someprivatekey' tron.default_address = 'someaddr' # tron.fromSun(tron.trx.get_balance('someaddr2')) #print(tron.trx.get_balance()) #print(tron.trx.get_account()) #print(tron.trx.get_account_resource()) Acc = tron.trx.get_account() SendAddr = 'someaddr3' UnfreezeEpoch = int(Acc['frozen'][0]['expire_time'] / 1000) FrozenBalance = float(tron.fromSun(Acc['frozen'][0]['frozen_balance'])) print(FrozenBalance - 10) print(strftime('%Y-%m-%d %H:%M:%S', localtime(UnfreezeEpoch))) print(strftime('%H:%M:%S', gmtime(UnfreezeEpoch - time()))) sleep(UnfreezeEpoch - (time() + 1.0)) #sleep(10 - (9 + 0.5)) x = 0 while x != 1: print(x) try: Ret = tron.trx.send_transaction(SendAddr, float(FrozenBalance - 10), {'message': 'testapi'}) print(Ret)
def execute(self, bot, update, args): if self.is_autobet(update): sql = self.get_resource("select_autobet.sql", plugin="autobet") res = self.execute_sql(sql, update.effective_user.id, plugin="autobet") if not res["success"] or not res["data"]: msg = f"{emo.ERROR} Autobet stopped. No data for user ID {update.effective_user.id}." self.if_autobet_then_stop(update, msg) update.message.reply_text(msg) return auto_chars = res["data"][0][1] auto_amount = str(res["data"][0][2]) args = [auto_chars, auto_amount] if len(args) != 2: update.message.reply_text(self.get_usage(), parse_mode=ParseMode.MARKDOWN) return chars = set(self.remove_unwanted(args[0].lower())) count = len(chars) amount = args[1] try: amount = float(amount) except: msg = f"{emo.ERROR} Provide a valid TRX amount" self.if_autobet_then_stop(update, msg) update.message.reply_text(msg) return # Check if user provided any valid characters if count == 0: msg = f"{emo.ERROR} No valid characters provided. Allowed are: `{self._VALID_CHARS}`" self.if_autobet_then_stop(update, msg) update.message.reply_text(msg, parse_mode=ParseMode.MARKDOWN) return # Bet need to be smaller than allowed characters (at least by one) if count >= (len(self._VALID_CHARS)): msg = f"{emo.ERROR} You need to provide 1-{len(self._VALID_CHARS)-1} characters and not {count}" self.if_autobet_then_stop(update, msg) update.message.reply_text(msg) return # Generate new betting address tron = Tron() account = tron.create_account tron.private_key = account.private_key tron.default_address = account.address.base58 addr = account.address.base58 # Check if generated address is valid if not bool(tron.isAddress(account.address.hex)): msg = f"{emo.ERROR} Generated wallet is not valid" update.message.reply_text(msg) return generated = { "pubkey": account.public_key, "privkey": account.private_key, "addr_hex": account.address.hex, "addr_base58": account.address.base58 } logging.info(f"{addr} TRX address created {generated} - {update}") # Default value for delaying a bet delay = 0 # Check last bet time and make sure that current # bet will be after 'bet_delay' time from config if not self.is_autobet(update): try: sql = self.get_resource("select_last_usr_bet.sql") res = self.execute_sql(sql, update.effective_user.id) uid = update.effective_user.id # No last bet for user found if not res["success"]: msg = f"{addr} Couldn't retrieve last bet for user {uid}. Delay = {delay}" logging.warning(msg) if not res["data"][0][0]: msg = f"{addr} Couldn't retrieve last bet for user {uid}. Delay = {delay}" logging.warning(msg) # Last bet for user found else: last_bet_date = datetime.strptime(res["data"][0][0], "%Y-%m-%d %H:%M:%S") bet_delay = res["data"][0][1] if res["data"][0][1] else 0 default_delay = self.config.get("bet_delay") delta = datetime.utcnow() - last_bet_date logging.info( f"{addr} Last bet for user {uid} was on {last_bet_date}. Delta is {delta}" ) if delta < timedelta(seconds=default_delay): delay = bet_delay + default_delay logging.info(f"{addr} Delay set to {delay} seconds") except Exception as e: logging.error(f"{addr} Couldn't determine bet delay: {e}") # Save generated address to database sql = self.get_resource("insert_address.sql") self.execute_sql(sql, account.address.base58, account.private_key) choice = "".join(sorted(chars)) leverage = self._LEVERAGE[len(chars)] # Save bet details to database sql = self.get_resource("insert_bet.sql") self.execute_sql(sql, account.address.base58, choice, update.effective_user.id, delay) # Get min and max amounts for this bet from config min_trx = self.config.get("min_trx") max_trx = self.config.get("max_trx") # Get users wallet to send bet TRX from sql = self.get_global_resource("select_address.sql") res = self.execute_global_sql(sql, update.effective_user.id) message = None if delay > 0: msg = f"{emo.WAIT} Bet will start in {delay} seconds..." message = update.message.reply_text(msg) logging.info(f"{addr} {msg}") time.sleep(delay) # Load message for user betting_msg = self.get_resource("betting.md") betting_msg = betting_msg.replace("{{choice}}", choice) betting_msg = betting_msg.replace("{{factor}}", str(leverage)) if self.is_autobet(update): msg = betting_msg.replace( "{{state}}", f"{emo.WAIT} AUTO-BET: Sending TRX from your wallet...") else: msg = betting_msg.replace( "{{state}}", f"{emo.WAIT} Sending TRX from your wallet...") # Send betting message to user if message: message = message.edit_text(msg, parse_mode=ParseMode.MARKDOWN) else: message = update.message.reply_text(msg, parse_mode=ParseMode.MARKDOWN) msg = msg.replace("\n", " ") logging.info(f"{addr} {msg}") manual_mode = False # User has a bot generated wallet if res["success"] and res["data"]: logging.info(f"{addr} Wallet for auto-send: {res['data']}") # Users existing wallet used for auto-send from_user = Tron() from_user.private_key = res["data"][0][2] from_user.default_address = res["data"][0][1] # Get balance (in "Sun") of users wallet address balance = from_user.trx.get_balance() trx_balance = from_user.fromSun(balance) logging.info( f"{addr} TRX Balance - Current: {trx_balance} - Needed: {amount + con.TRX_FEE}" ) # Not enough balance for auto-send if trx_balance < (amount + con.TRX_FEE): # Bet is an auto-bet if self.is_autobet(update): msg = f"{emo.ERROR} Autobet stopped. Not enough balance." self.if_autobet_then_stop(update, f"{addr} {msg}") update.message.reply_text(msg) return # Bet is a manually started bet else: logging.warning( f"{addr} Couldn't auto-send. Not enough balance.") manual_mode = True # Enough balance for auto-send else: try: # Send bet amount from user wallet to generated wallet send = from_user.trx.send(tron.default_address.hex, amount) # Transaction didn't went through if "code" in send and "message" in send: if self.is_autobet(update): msg = f"{emo.ERROR} Autobet stopped. Can't send {amount} TRX: {send['message']}" self.if_autobet_then_stop(update, f"{addr} {msg}") update.message.reply_text(msg) return else: logging.warning( f"{addr} Couldn't auto-send: {send}") manual_mode = True else: if self.is_autobet(update): msg = f"{emo.DONE} AUTO-BET: Successfully sent `{amount}` TRX to `{addr}`" else: msg = f"{emo.DONE} Successfully sent `{amount}` TRX to `{addr}`" logging.info(f"{addr} {msg} - {send}") betting_msg = betting_msg.replace("{{state}}", msg) message.edit_text(betting_msg, parse_mode=ParseMode.MARKDOWN) except Exception as e: if self.is_autobet(update): msg = f"{emo.ERROR} Autobet stopped. Can't send {amount} TRX: {e}" self.if_autobet_then_stop(update, f"{addr} {msg}") update.message.reply_text(msg) return else: logging.warning(f"{addr} Couldn't auto-send: {e}") manual_mode = True # User doesn't have a bot generated wallet else: # Bet is an auto-bet if self.is_autobet(update): msg = f"{emo.ERROR} Autobet stopped. Generate a wallet first with /start" self.if_autobet_then_stop(update, f"{addr} {msg}") update.message.reply_text(msg) return else: logging.warning( f"{addr} Couldn't auto-send: User doesn't have a wallet") manual_mode = True if manual_mode: msg = "*Wallet balance not sufficient*. " msg += f"Send between *{min_trx}* and *{max_trx}* TRX to following address:\n\n`{addr}`" betting_msg = betting_msg.replace("{{state}}", msg) message.edit_text(betting_msg, parse_mode=ParseMode.MARKDOWN) betting_msg = betting_msg.replace("\n", " ") logging.info(f"{addr} {betting_msg}") # --- General logic --- first = self.config.get("check_start") check = self.config.get("balance_check") context = { "tron": tron, "choice": choice, "update": update, "start": time.time(), "message": message, "sc_trx": 0, # Second chance TRX value "sc_win": False # Second chance won or not } self.repeat_job(self.scan_balance, check, first=first, context=context) logging.info(f"{addr} Initiated repeating job")
class TronApi: def __init__(self): self.tron = Tron() self.api = 'https://api.trongrid.io/' self.session = aiohttp.ClientSession(conn_timeout=3600) async def _request(self, method, endpoint, **params): async with self.session.request(method, self.api + endpoint, json=params) as r: return await r.json(content_type='') def is_address(self, addr): try: return is_address(addr) except: return False async def get_balance(self, addr): account = await self._request('POST', 'wallet/getaccount', address=str( self.tron.address.to_hex(addr))) if 'balance' not in account: return 0 return self.tron.fromSun(account['balance']) async def get_token_info(self, token_id): token_info = await self._request('POST', 'wallet/getassetissuebyid', value=token_id) return token_info async def _get_block(self, number=None): if not number: return await self._request('POST', 'wallet/getnowblock') return await self._request('POST', 'wallet/getblockbynum', num=number) async def create_wallet(self): account = self.tron.create_account return account.address.base58, account.private_key def from_hex(self, text): return base58.b58encode_check(bytes.fromhex(text)) def to_hex(self, text): return codecs.encode(base58.b58decode_check(text), 'hex').decode() async def send_trx(self, from_address, private_key, to_address, amount): account = Tron(private_key=private_key, default_address=from_address) account_api = Trx(account) amount_sun = amount * 1e6 tx = await self._request('POST', '/wallet/createtransaction', owner_address=self.to_hex( from_address.encode()), to_address=self.to_hex(to_address.encode()), amount=int(amount_sun)) signed_tx = account_api.sign(tx) return await self._request('POST', '/wallet/broadcasttransaction', **signed_tx) async def send_token(self, from_address, private_key, to_address, token_id, amount): account = Tron(private_key=private_key, default_address=from_address) account_api = Trx(account) amount_sun = amount * 1e6 tx = await self._request( 'POST', '/wallet/transferasset', owner_address=self.to_hex(from_address.encode()), to_address=self.to_hex(to_address.encode()), amount=int(amount_sun), asset_name=codecs.encode(str(token_id).encode(), 'hex').decode()) signed_tx = account_api.sign(tx) return await self._request('POST', '/wallet/broadcasttransaction', **signed_tx)