Using Machine Learning with Telegram for 1XBet Prediction

A4s1kk
5 min readAug 9, 2024

--

In the rapidly evolving world of online gaming and betting, predictive analytics powered by machine learning (ML) is becoming increasingly popular. This tutorial will walk you through building a simple yet effective machine learning model to predict outcomes on 1XBet, specifically focusing on the “Crash” game. We will also integrate a Telegram bot to send predictions directly to your phone or chat group.

Step 1: Setting Up Your Environment

Before diving into the code, ensure your environment is ready. You need to install the required dependencies and tools. We’ll be using Python, Selenium, and scikit-learn for our machine learning model, along with Telebot for Telegram integration.

Here’s a quick setup guide:

  1. Docker Setup: Use Docker to containerize your application, ensuring consistent environments and dependencies.

Dockerfile:

FROM python:3.12.1

WORKDIR /app
COPY . /app

# Install Python dependencies
RUN pip install -r requirements.txt

# Install necessary packages and dependencies for Chrome, ChromeDriver, and Xvfb
RUN apt-get update && \
apt-get install -y wget unzip xvfb libxi6 libgconf-2-4 libnss3 libxss1 libasound2 libgbm-dev && \
wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - && \
echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list && \
apt-get update && \
apt-get install -y google-chrome-stable && \
rm -rf /var/lib/apt/lists/* && \
apt-get clean && \
wget https://chromedriver.storage.googleapis.com/LATEST_RELEASE -O /tmp/chromedriver_latest && \
CHROMEDRIVER_VERSION=$(cat /tmp/chromedriver_latest) && \
wget https://chromedriver.storage.googleapis.com/${CHROMEDRIVER_VERSION}/chromedriver_linux64.zip -P /tmp && \
unzip /tmp/chromedriver_linux64.zip -d /usr/local/bin && \
rm /tmp/chromedriver_linux64.zip /tmp/chromedriver_latest

# Start Xvfb and run the script
CMD ["bash", "-c", "Xvfb :99 -screen 0 1024x768x16 & export DISPLAY=:99 && python 1XBetCrashUpdater.py"]

2. Requirements File: Ensure your requirements.txt is in place for easy dependency management.

requirements.txt:

pandas==2.2.2
scikit-learn==1.5.0
telebot==0.0.5
selenium==4.21.0
webdriver-manager==4.0.1

Step 2: Data Collection

To build an effective model, you need data. The 1XBetCrashUpdater.py script helps you scrape real-time multiplier data from 1XBet's Crash game.

1XBetCrashUpdater.py:

import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager

# Define the URL of the website
url = "https://1xbet.com/en/allgamesentrance/crash"
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')

driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=chrome_options)

while True:
try:
# Navigate to the website
driver.get(url)
multiplier_element = driver.find_element(By.CSS_SELECTOR,'.c-events-table__multiplier')

while not multiplier_element.is_displayed():
time.sleep(0.1)

# Get the multiplier value
multiplier = float(multiplier_element.text[1:])
print(f"Multiplier: {multiplier}")

except Exception as e:
print(f"Error: {e}")
time.sleep(1)
driver.quit()

This script continuously fetches the multiplier values from the Crash game and prints them to your console. You can extend this script to store data in a CSV file for later use. (NOTE: THIS SCRIPT CAN’T DIRECTLY GET THE VALUES; YOU HAVE TO FIND IT MANUALLY)

Step 3: Building the Machine Learning Model

Now, let’s build a machine learning model to predict future multipliers based on historical data. We’ll use a variety of models to see which one works best.

Crash.py:

import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.neural_network import MLPRegressor
from sklearn.model_selection import train_test_split
import telebot
from telebot.types import Message

# Load the data into a Pandas DataFrame
df = pd.read_csv('1XBetCrash.csv')

# Extract the 'Multiplier' column from the DataFrame
y = df['Multiplier']

# Drop the 'Time' and 'Multiplier' columns from the DataFrame
X = df.drop(columns=['Time', 'Multiplier'])

# Normalize the data using StandardScaler
scaler = StandardScaler()
X = scaler.fit_transform(X)

# Split the data into training and test sets
train_X, test_X, train_y, test_y = train_test_split(X, y, test_size=0.3, random_state=123)

# Train multiple models
linear_reg = LinearRegression()
linear_reg.fit(train_X, train_y)

tree_reg = DecisionTreeRegressor(random_state=123)
tree_reg.fit(train_X, train_y)

forest_reg = RandomForestRegressor(n_estimators=100, random_state=123)
forest_reg.fit(train_X, train_y)

nn_reg = MLPRegressor(hidden_layer_sizes=(100,), max_iter=1000, random_state=123)
nn_reg.fit(train_X, train_y)

# Create a Telegram bot object
bot = telebot.TeleBot('YOUR_TOKEN')

# Define the handler function for the '/predict' command
@bot.message_handler(commands=['predict'])
def handle_predict(message: Message):
# Get the chat ID of the user who sent the message
chat_id = message.chat.id

# Use the trained models to predict the next 10 values of the multiplier
for model in [linear_reg, tree_reg, forest_reg, nn_reg]:
predictions = []
for i in range(1, 11):
next_X = X[-i].reshape(1, -1)
next_y = model.predict(next_X)[0]
predictions.append("Prediction {}: {}".format(i, next_y))

# Send a separate message for each model's predictions
bot.send_message(chat_id=chat_id, text="Based on Model: {}".format(model.__class__.__name__))
bot.send_message(chat_id=chat_id, text='\n'.join(predictions))

# Start the bot
bot.polling()

This script builds several machine learning models to predict the next multiplier value:

  • Linear Regression
  • Decision Tree Regressor
  • Random Forest Regressor
  • Neural Network Regressor

Once trained, these models can predict the next few values of the multiplier based on the input data.

Step 4: Integrating Telegram Bot

The final piece is integrating the machine learning model with Telegram using the telebot library. This allows you to send commands like /predict to your bot, which will then reply with predictions based on your trained models.

Replace 'YOUR_TOKEN' with your actual Telegram bot token. The bot will listen for commands and respond with predictions.

Step 5: Running Everything Together

With everything set up, you can now run the Docker container, which will start the script, scrape data, and make predictions that are sent directly to your Telegram bot.

To run the Docker container:

docker build -t 1xbet-predictor .
docker run -d 1xbet-predictor

Get the full code from here: https://github.com/aa-sikkkk/FortuneTeller

Conclusion

By following this guide, you have built a basic machine learning pipeline to predict outcomes in the 1XBet Crash game. The integration with Telegram makes it easy to receive predictions on the go, enabling you to make more informed decisions. This project can be extended with more sophisticated models and data collection techniques, turning it into a powerful tool for predictive analytics in online betting.

Ready to Level Up Your Python Skills?

EscapeMantra: The Ultimate Python Ebook” is here to guide you through every step of mastering Python. Whether you’re new to coding or looking to sharpen your skills, this ebook is packed with practical examples, hands-on exercises, and real-world projects to make learning both effective and enjoyable.

Here’s what you’ll get:

  • Clear Explanations: Understand Python concepts easily with straightforward guidance.
  • Engaging Projects: Work on fun projects like a Snake game and an AI Chatbot to apply what you’ve learned.
  • Hands-On Practice: Build your skills with exercises designed to boost your confidence.

👉 Grab your copy. Dive in today and start mastering Python at your own pace. Don’t wait — your programming journey starts now!

🚀 Support My Work and Get More Exclusive Content! 🚀

If you found article helpful and want to see more in-depth content, tools, and exclusive resources, consider supporting me on Patreon. Your support helps me create and share valuable content, improve projects, and build a community of passionate developers.

👉 Become a Patron Today! Join here to access exclusive source codes, early project releases, and more!

Thank you for your support and for being part of this journey!

--

--