HELP! Replit stops automatically after I run it

Question:

Please help, this is my discord bot’s code and the replit stops automatically after I run it, my other discord bot replits works tho and repl of those don’t glitch like this

Repl link/Link to where the bug appears:

https://replit.com/@AdenLLT/nthing

Screenshots, links, or other helpful context:

Keeps appearing like this after I run and stops:

I’ve tried everything, from making a new repl to anything else. Please help.

import discord
import os
import json
import random
import sqlite3
import pickle
import asyncio
from discord.ext import commands, tasks
from discord.ext.commands.cooldowns import BucketType

intents = discord.Intents.default()
intents.members = True
intents.message_content = True

bot = commands.Bot(
    command_prefix="_",
    description="",
    intents=intents,
    case_insensitive=True,
    strip_after_prefix=True,
)


def get_player_stats(player_name):
    stats = {
        "batting_runs": 0,
        "batting_balls": 0,
        "bowling_runs": 0,
        "bowling_wickets": 0,
        "bowling_overs": 0,
    }
    # Load the player's stats from a database or file
    # Replace this with your own implementation

    return stats


def update_player_stats(player_name, stat_type, value):
    # Update the player's stats in the database or file
    # Replace this with your own implementation

    pass


@bot.listen()
async def on_ready():
    print("On it")


@bot.listen()
async def on_command_error(ctx, error):
    await ctx.send(str(error))

    # Define your team names

    team1_name = "Random ass team"
    team2_name = "TFH Agents"
    team1 = [
        "Zodiac",
        "Immm",
        "Lohit",
        "Phoenix",
        "Ahadsg",
        "Ansh",
        "Aaarav",
        "Arnav",
        "Aden",
        "Superlegendary",
        "Ashoka",
    ]
    team2 = [
        "Bot2",
        "Bot1",
        "Sharky",
        "Hamster",
        "Brownie",
        "AshokaGF",
        "Arhaan",
        "Samir",
        "Hamza",
        "Raptor",
        "Rusher",
    ]

    # Define a check function to check if the user has the required user ID

    def is_allowed_user(ctx):
        allowed_user_id = 765965975761715241  # Replace with the actual user ID
        return ctx.author.id == allowed_user_id

    @bot.command()
    @commands.check(is_allowed_user)
    async def startsim(ctx):
        global team1, team2
        if random.randint(0, 1) == 0:
            batting, bowling = (
                team1.copy(),
                team2.copy(),
            )  # Keep the order of batting and bowling
        else:
            batting, bowling = (
                team2.copy(),
                team1.copy(),
            )  # Keep the order of batting and bowling
        print(len(batting), len(bowling))  # Debugging print statement

        await game_simulation(ctx, batting, bowling)

    async def game_simulation(ctx, batting, bowling):
        overs = 20
        total_runs = [0, 0]
        total_wickets = [0, 0]
        batsmen_runs = [0, 0]
        batsmen_balls = [0, 0]
        bowler_runs = [0] * 11
        bowler_wickets = [0] * 11
        bowler_overs = [0] * 11
        batsman_in = [True, True]
        timeline = []
        partnership_runs = 0
        partnership_balls = 0
        striker = 0
        run = 0

        half_century_gif_sent = False
        century_gif_sent = False

        for innings in range(2):
            # Reset the striker's and non-striker's runs at the start of each innings

            batsmen_runs = [0, 0]
            batsmen_balls = [0, 0]
            if innings == 0:
                striker = 0
            else:
                striker = 1
            # Reset the bowler's figures at the start of each innings

            bowler_runs = [0] * 11
            bowler_wickets = [0] * 11
            bowler_overs = [0] * 11
            # Reset the partnership at the start of each innings

            partnership_runs = 0
            partnership_balls = 0

            # Reset the timeline at the start of each innings

            timeline.clear()

            if innings == 1:
                batting.reverse()  # Reverse batting order
                bowling.reverse()  # Reverse bowling order
                total_runs = [0, 0]  # Reset total runs for the second innings
                total_wickets = [0, 0]  # Reset total wickets for the second innings
            for over in range(overs):
                for ball in range(6):
                    if total_wickets[innings] == 10 or (
                        innings == 1 and total_runs[1] > total_runs[0]
                    ):
                        break
                    await asyncio.sleep(5)
                    outcome = random.choices(
                        population=[0, 1, 2, 3, 4, 5, 6, "W"],
                        weights=[10, 20, 20, 10, 10, 10, 10, 9999],
                        k=1,
                    )[0]

                    if outcome == "W":
                        total_wickets[innings] += 1
                        bowler_wickets[over % 11] += 1
                        await ctx.send("🔴")
                        timeline.append("🔴")

                        if (total_wickets[innings] + 1) <= len(
                            batting
                        ):  # Update this condition
                            # The batsman who got out

                            out_batsman = batting[striker]
                            striker += 1  # Change striker to the next batsman

                            # Reset runs and balls for the batsman who got out

                            batsman_idx = 0 if striker == 0 else 1
                            batsmen_runs[batsman_idx] = 0
                            batsmen_balls[batsman_idx] = 0
                            batsman_in[batsman_idx] = False

                            # Add new batsman to the crease at striker's position

                            if len(batting) > 0:
                                next_batsman = batting.pop()
                                batsman_in[striker] = True
                                partnership_runs = 0
                                partnership_balls = 0
                                batsmen_runs[striker] = 0
                                batsmen_balls[striker] = 0
                            else:
                                batsman_in[striker] = False
                            # Commentary

                            fielder = random.choice(
                                bowling
                            )  # Changed to include only bowling side players as fielders
                            commentary = (
                                f"{out_batsman} is out! Caught out by {fielder}"
                            )
                            await ctx.send(commentary)

                            # Update player's stats

                            for player in batting + bowling:
                                if player == out_batsman:
                                    continue
                                stats = get_player_stats(player)
                                update_player_stats(
                                    player, "bowling_runs", bowler_runs[over % 11]
                                )
                                update_player_stats(
                                    player, "bowling_wickets", bowler_wickets[over % 11]
                                )
                        else:
                            break
                    else:
                        # Remaining code goes here

                        # Remaining code goes here

                        run = outcome
                        batsman_idx = 0 if striker == 0 else 1
                        batsmen_runs[batsman_idx] += run
                        batsmen_balls[batsman_idx] += 1
                        bowler_runs[over % 11] += run
                        partnership_runs += run
                        partnership_balls += 1
                        await ctx.send(f"{run}️⃣")
                        timeline.append(f"{run}️⃣")
                        if run % 2 == 1:
                            # Swap strike

                            striker = 1 if striker == 0 else 0
                        # Update total runs according to the current innings

                        total_runs[innings] += run

                        # Check for half century (50+ runs)

                        if (
                            batsmen_runs[batsman_idx] >= 50
                            and run == 0
                            and not half_century_gif_sent
                        ):
                            player_name = batting[striker]
                            half_century_message = (
                                f"**{player_name} GOT A HALF CENTURY!**"
                            )
                            half_century_gif = random.choice([
                                "https://kulfyapp.com/kulfy/36HBTL",
                                "https://tenor.com/bRK9w.gif",
                                "https://tenor.com/sPMFn2hmxkk.gif",
                            ])
                            await ctx.send(half_century_message)
                            await ctx.send(half_century_gif)
                            half_century_gif_sent = True
                        # Check for century (100+ runs)

                        if (
                            batsmen_runs[batsman_idx] >= 100
                            and run == 0
                            and not century_gif_sent
                        ):
                            player_name = batting[striker]
                            century_message = f"**{player_name} GOT A CENTURY!**"
                            century_gif = random.choice([
                                "https://tenor.com/nmfnKvEdnpA.gif",
                                "https://tenor.com/b0prL.gif",
                                "https://tenor.com/fkpVJrxIDgE.gif",
                            ])
                            await ctx.send(century_message)
                            await ctx.send(century_gif)
                            century_gif_sent = True
                        # Update player's stats

                        for player in batting + bowling:
                            stats = get_player_stats(player)
                            update_player_stats(
                                player, "batting_runs", batsmen_runs[batsman_idx]
                            )
                            update_player_stats(
                                player, "batting_balls", batsmen_balls[batsman_idx]
                            )
                    # Get the current batsman

                    if striker == 0:
                        current_batsman = batting[-2]
                    else:
                        current_batsman = batting[-1]
                    # Get the current bowler and their bowling length

                    current_bowler = bowling[over % 11]

                    # Define possible shots and bowling lengths

                    shots = [
                        "defensive",
                        "drive",
                        "pull",
                        "hook",
                        "sweep",
                        "cut",
                        "flick",
                        "glance",
                    ]
                    lengths = ["short", "full", "good length"]

                    # Generate random shot and length

                    shot = random.choice(shots)
                    length = random.choice(lengths)

                    # Generate commentary based on shot, length, batsman, and bowler

                    commentary = (
                        f"{current_batsman} played a {shot} shot on a {length} ball"
                        f" bowled by {current_bowler}."
                    )
                    commentary += f" The result is {run} runs!"

                    # Skip commentary if batsman has 0 runs

                    if batsmen_runs[striker] != 0:
                        # Send commentary

                        await ctx.send(commentary)
                    embed = discord.Embed(
                        title="Cricket Simulation Game",
                        description=f"Innings {innings + 1}, Over {over}.{ball + 1}",
                        color=0x00FF00,
                    )

                    # Update batsmen who are currently in

                    batting_str = ""
                    for idx, batsman in enumerate(batting[-2:]):
                        prefix = "*" if batsman_in[idx] else ""
                        batting_str += (
                            f"{prefix}{batsman}:"
                            f" {batsmen_runs[idx]}({batsmen_balls[idx]}){'*' if idx == striker else ''}"
                        )
                        if idx < 1:
                            batting_str += ", "
                    embed.add_field(
                        name="Batting", value=f"`{batting_str}`", inline=True
                    )
                    embed.add_field(
                        name="Bowling",
                        value=(
                            f"`{bowling[over % 11]}:"
                            f" {bowler_runs[over % 11]}/{bowler_wickets[over % 11]} ({bowler_overs[over % 11]}.{ball + 1})`"
                        ),
                        inline=True,
                    )
                    embed.add_field(
                        name="Partnership",
                        value=f"P'Ship: {partnership_runs}({partnership_balls})",
                    )

                    # Add current total of both teams to the embed field

                    if innings == 0:
                        embed.add_field(
                            name="Current Total",
                            value=(
                                f"`{team1_name}:"
                                f" {total_runs[innings]}/{total_wickets[innings]} ({over}.{ball + 1}/20.0)\n{team2_name}:"
                                " Yet To Bat`"
                            ),
                            inline=True,
                        )
                        current_run_rate = total_runs[innings] / (
                            (over * 6 + ball + 1) / 6
                        )
                        embed.set_footer(
                            text=f"Current Run Rate: {current_run_rate:.2f}"
                        )
                    else:
                        embed.add_field(
                            name="Current Total",
                            value=(
                                f"`{team2_name}:"
                                f" {total_runs[innings]}/{total_wickets[innings]} ({over}.{ball + 1}/20.0)\n{team1_name}:"
                                f" {total_runs[0]}/{total_wickets[0]}`"
                            ),
                            inline=True,
                        )
                        remaining_balls = (20 * 6) - ((over * 6) + ball + 1)
                        remaining_runs = total_runs[0] - total_runs[1] + 1
                        embed.set_footer(
                            text=(
                                f"{team2_name} Needs {remaining_runs} in"
                                f" {remaining_balls} balls to win."
                            )
                        )
                    # Add timeline to the embed field

                    if ball == 5:
                        timeline.append("|")
                    timeline_str = " ".join(timeline[-12:])
                    embed.add_field(name="Timeline", value=timeline_str, inline=False)

                    await ctx.send(embed=embed)
            if total_wickets[innings] == 10 or (
                innings == 1 and total_runs[1] > total_runs[0]
            ):
                break
            bowling.reverse()  # Reverse bowling order
            bowling.append(bowling.pop(0))
            bowler_overs[over % 11] += 1

            if total_runs[0] > total_runs[1]:
                winner = team1_name
            elif total_runs[0] < total_runs[1]:
                winner = team2_name
            else:
                winner = "Draw"
            # Send results and stats

            await ctx.send("The match is over. Here are the results and stats:")

            # Winner announcement

            await ctx.send(f"The result is: {winner}")

            # Man of the match

            man_of_the_match = random.choice(batting + bowling)
            await ctx.send(f"The man of the match is: {man_of_the_match}")

            # Batting figures

            batting_figures = "Batting figures:\n"
            for idx, batsman in enumerate(batting):
                stats = get_player_stats(batsman)
                batting_figures += (
                    f"{batsman}: {stats['batting_runs']}({stats['batting_balls']})\n"
                )
            await ctx.send(batting_figures)

            # Bowling figures

            bowling_figures = "Bowling figures:\n"
            for idx, bowler in enumerate(bowling):
                stats = get_player_stats(bowler)
                bowling_figures += (
                    f"{bowler}:"
                    f" {stats['bowling_runs']}/{stats['bowling_wickets']} ({stats['bowling_overs']})\n"
                )
            await ctx.send(bowling_figures)

            bot.run(os.environ["TOKEN"])

Hello, faced with the same problem, and did not find a solution?

@AdenLLT I think you just need to unindent the line where you call bot.run.

4 Likes

remove the env file, and do TOKEN = os.getenv(TOKEN) or whatever it is named in the “secrets” tab.

bot.run isn’t the problem, the code can’t run the bot token, so it would have to be defined to get it from the “secrets” tab.

oh, also the bot.run should look like this now:
bot.run(TOKEN) (remove the double quotes in the parentheses)

I think you’re a bit confused @thehaseltons. The way OP’s code is right now is getting the bot token from the secrets tab.

os.environ[] is pretty much the same as os.environ.get or os.getenv except it will error if it does not find the secret.

1 Like

Oh Right, Sorry, I forgot that can be worded the same way.

Have you pip installed everything?

If they didn’t, it would have shown an error.

oh yeah. I used to have this problem on other websites too. (I think it happened most with my Dinosaur Game, because I used to many threads)