For some reason it's not working the way I planned to

if i don’t import my bot to server the run part only run the server part but not the bot, if i import the bot the bot runs but don’t works. What am i doing wrong? It’s suppose to run server with my bot function
https://replit.com/@HirukaRogue

entrypoint = "bot.py"
modules = ["python-3.10:v18-20230807-322e88b"]

hidden = [".pythonlibs"]

[nix]
channel = "stable-23_05"

[deployment]
run = ["sh", "-c", "bot.py"]

Okay soo, according to you i need to read the docs for run part or… i have no idea what is not working here. Maybe i should add server.py?

okay so, i have no idea how i add my server.py, if i add to my bot.py it only runs my server.py if i add bot.py in my server it only runs my bot

So you want to run server.py? Which is the main file in the program?

bot.py, my server.py is the server part that i don’t know how i startup in my repl, and i need to startup it somehow to allow my bot to keep running even if my pc is shutdown, which when shut down it stops working

@HirukaRogue Ok. Your .replit file is correct, don’t change anything there.
Do you have a web framework with your bot? A web element of any kind?

@HirukaRogue Try opening it in a new tab, and click Reload and press the CTRL button at the same time. Don’t let go of CTRL when it is reloading. Only remove it when it has fully loaded.
This will clear the cache of the site.

okay so, the reload button is from my navigator, or…?

@NateDhaliwal i have a question, if i instad of flat calling keepAlive, can i instead call keep alive from my bot.py? Will it work?

okay i got what happened, Flask don’t seems to support aynchronous, i need to change it to be an asynchronous function, otherwise my bot won’t load

import bot_token
import discord
from discord import app_commands
import asyncio
from discord.ext import commands
import os
from rpu_database import Database
from urllib import parse
import server

bot_status = ["initializing", "active", "shutting down"]
DEFAULT_PREFIX = "rpu->"
EXTENSIONS = [
    'jishaku',
]
INTENTS = discord.Intents.default()
INTENTS.message_content = True


class Bot(commands.Bot):

  def __init__(self) -> None:
    super().__init__(
        intents=INTENTS,
        command_prefix=prefix_setup,
        case_insensitive=True,
    )
    self.database = Database()
    print("Bot Connected!")

  async def setup_hook(self) -> None:
    # username = parse.quote_plus(os.environ['db_username'])
    # password = parse.quote_plus(os.environ['db_password'])
    # db_name = "rpucloudserver"  # or whatever your database name is
    # connection_uri = f"mongodb+srv://{username}:{password}@{db_name}.bscpl0p.mongodb.net/?retryWrites=true&w=majority"
    # username = os.environ['db_username']
    # password = os.environ['db_password']
    # db_name = "rpucloudserver"
    # url_template = f"mongodb+srv://{username}:{password}@{db_name}.bscpl0p.mongodb.net/?retryWrites=true&w=majority"

    # encoded_url = parse.quote(url_template, safe='')
    # # print(encoded_url)
    # # await self.database.connect(connection_uri)
    # await self.database.connect(encoded_url)
    for extension in EXTENSIONS:
      await self.load_extension(extension)
    await self.add_cog(PrefixCog(self))
    for filename in os.listdir("./cogs"):
      if filename.endswith(".py"):
        await self.load_extension(f"cogs.{filename[:-3]}")
    guild = discord.Object(1135999359985647706)
    await self.tree.sync()
    server.keep_alive()

  async def close(self) -> None:
    await super().close()
    # await self.database.close()


async def prefix_setup(bot, message):
  prefix = await bot.database.get_prefix(guild_id=message.guild.id)
  if prefix:
    return prefix
  else:
    return DEFAULT_PREFIX


class PrefixCog(commands.Cog):

  def __init__(self, bot: Bot) -> None:
    self.bot = bot

  @commands.hybrid_group(name="prefix",
                         fallback="help",
                         invoke_without_command=True)
  async def _prefix(self, ctx: commands.Context, *, prefix: str) -> None:
    await ctx.send(
        "Use this command to set or reset the this bot prefix in your server")

  @_prefix.command(name="set")
  async def _prefix_set(self, ctx: commands.Context, *, prefix: str) -> None:
    await self.bot.database.set_prefix(guild_id=ctx.guild.id, prefix=prefix)
    await ctx.send(f"Prefix set to `{prefix}`.")

  @_prefix.command(name="reset")
  async def _prefix_reset(self, ctx: commands.Context) -> None:
    await self.bot.database.remove_prefix(guild_id=ctx.guild.id)
    await ctx.send(f"The prefix has been reset to `{DEFAULT_PREFIX}`.")


Bot().run(bot_token.return_token())
from flask import Flask

app = Flask(__name__)


@app.route('/')
def home():
  return "Bot is running!"


def keep_alive():
  app.run(host='0.0.0.0', port=3000)

How to i execute Flask as asynchronous, so my bot and server works together

1 Like

Jurry rigging failed

Traceback (most recent call last):
  File "/home/runner/RP-Utilities-Beta/bot.py", line 9, in <module>
    import server
  File "/home/runner/RP-Utilities-Beta/server.py", line 24, in <module>
    loop.run_until_complete(server_bot_synchrony())
  File "/nix/store/xf54733x4chbawkh1qvy9i1i4mlscy1c-python3-3.10.11/lib/python3.10/asyncio/base_events.py", line 649, in run_until_complete
    return future.result()
  File "/home/runner/RP-Utilities-Beta/server.py", line 19, in server_bot_synchrony
    await bot.run_bot()
  File "/home/runner/RP-Utilities-Beta/bot.py", line 91, in run_bot
    Bot().run(bot_token.return_token())
  File "/home/runner/RP-Utilities-Beta/.pythonlibs/lib/python3.10/site-packages/discord/client.py", line 862, in run
    asyncio.run(runner())
  File "/nix/store/xf54733x4chbawkh1qvy9i1i4mlscy1c-python3-3.10.11/lib/python3.10/asyncio/runners.py", line 33, in run
    raise RuntimeError(
RuntimeError: asyncio.run() cannot be called from a running event loop
import bot
from flask import Flask

import asyncio

app = Flask(__name__)


@app.route('/')
def home():
  return "Bot is running!"


async def keep_alive():
  app.run(host='0.0.0.0', port=3000)


async def server_bot_synchrony():
  await bot.run_bot()
  await keep_alive()


loop = asyncio.get_event_loop()
loop.run_until_complete(server_bot_synchrony())
import bot_token
import discord
from discord import app_commands
import asyncio
from discord.ext import commands
import os
from rpu_database import Database
from urllib import parse
import server

bot_status = ["initializing", "active", "shutting down"]
DEFAULT_PREFIX = "rpu->"
EXTENSIONS = [
    'jishaku',
]
INTENTS = discord.Intents.default()
INTENTS.message_content = True


class Bot(commands.Bot):

  def __init__(self) -> None:
    super().__init__(
        intents=INTENTS,
        command_prefix=prefix_setup,
        case_insensitive=True,
    )
    self.database = Database()
    print("Bot Connected!")

  async def setup_hook(self) -> None:
    # username = parse.quote_plus(os.environ['db_username'])
    # password = parse.quote_plus(os.environ['db_password'])
    # db_name = "rpucloudserver"  # or whatever your database name is
    # connection_uri = f"mongodb+srv://{username}:{password}@{db_name}.bscpl0p.mongodb.net/?retryWrites=true&w=majority"
    # username = os.environ['db_username']
    # password = os.environ['db_password']
    # db_name = "rpucloudserver"
    # url_template = f"mongodb+srv://{username}:{password}@{db_name}.bscpl0p.mongodb.net/?retryWrites=true&w=majority"

    # encoded_url = parse.quote(url_template, safe='')
    # # print(encoded_url)
    # # await self.database.connect(connection_uri)
    # await self.database.connect(encoded_url)
    for extension in EXTENSIONS:
      await self.load_extension(extension)
    await self.add_cog(PrefixCog(self))
    for filename in os.listdir("./cogs"):
      if filename.endswith(".py"):
        await self.load_extension(f"cogs.{filename[:-3]}")
    guild = discord.Object(1135999359985647706)
    await self.tree.sync()

  async def close(self) -> None:
    await super().close()
    # await self.database.close()


async def prefix_setup(bot, message):
  prefix = await bot.database.get_prefix(guild_id=message.guild.id)
  if prefix:
    return prefix
  else:
    return DEFAULT_PREFIX


class PrefixCog(commands.Cog):

  def __init__(self, bot: Bot) -> None:
    self.bot = bot

  @commands.hybrid_group(name="prefix",
                         fallback="help",
                         invoke_without_command=True)
  async def _prefix(self, ctx: commands.Context, *, prefix: str) -> None:
    await ctx.send(
        "Use this command to set or reset the this bot prefix in your server")

  @_prefix.command(name="set")
  async def _prefix_set(self, ctx: commands.Context, *, prefix: str) -> None:
    await self.bot.database.set_prefix(guild_id=ctx.guild.id, prefix=prefix)
    await ctx.send(f"Prefix set to `{prefix}`.")

  @_prefix.command(name="reset")
  async def _prefix_reset(self, ctx: commands.Context) -> None:
    await self.bot.database.remove_prefix(guild_id=ctx.guild.id)
    await ctx.send(f"The prefix has been reset to `{DEFAULT_PREFIX}`.")


async def run_bot():
  Bot().run(bot_token.return_token()