Python Example
This page contains a Toxi Bot integration example in Python
Last updated
This page contains a Toxi Bot integration example in Python
Last updated
The code below is simply an interpretation of a TypeScript code from the previous page. We strongly recommend you reading the previous page even if you're not familiar with TypeScript because it contains some useful language-agnostic explanations.
The following code presents a ToxiBotClient
class that acts as an abstraction for communicating with Toxi Bot via npm package.
# pip install telethon
from telethon import TelegramClient
from telethon.sessions import StringSession
from typing import Optional, Any
import asyncio
class ToxiBotClient:
bot_username = "@toxi_solana_bot"
_bot_chat_id: Optional[int] = None
def __init__(self, api_id: int, api_hash: str, session_id: str):
self._client = TelegramClient(
StringSession(session_id), api_id, api_hash, connection_retries=5
)
async def connect(self) -> None:
if not await self._client.is_connected():
await self._client.connect()
async def send_message_to_bot(self, message: str) -> Any:
chat_id = self._bot_chat_id or self.bot_username
msg = await self._client.send_message(chat_id, message)
if not self._bot_chat_id and msg.chat_id:
self._bot_chat_id = msg.chat_id
return msg
async def send_buy_command(self, token_mint: str, buy_amount: float) -> Any:
return await self.send_message_to_bot(f"/buy {token_mint} {buy_amount}")
async def send_sell_command(self, token_mint: str, sell_percentage: int) -> Any:
return await self.send_message_to_bot(f"/sell {token_mint} {sell_percentage}%")
@classmethod
async def create_new_session(
cls,
api_id: int,
api_hash: str,
phone_number: str,
password: Optional[str] = None,
) -> str:
client = TelegramClient(StringSession(), api_id, api_hash, connection_retries=5)
await client.start(
phone=phone_number,
password=password,
code_callback=lambda: input(f"Enter Telegram code for {phone_number}: "),
)
return client.session.save()
async def main():
# Create new session
session_str = await ToxiBotClient.create_new_session(
api_id=YOUR_API_ID,
api_hash="YOUR_API_HASH",
phone_number="+1234567890",
password="2FA_PASSWORD_IF_ANY",
)
print("Session string:", session_str)
# Initialize client with existing session
client = ToxiBotClient(
api_id=YOUR_API_ID, api_hash="YOUR_API_HASH", session_id=session_str
)
await client.connect()
# Send commands
await client.send_buy_command("TOKEN_MINT_ADDRESS", 0.5)
await client.send_sell_command("TOKEN_MINT_ADDRESS", 50)