1

I am trying to make an unblocked version of Discord using my own web-app using Flask, and have it show messages from a discord server. I have the following code:

from flask import Flask, render_template, redirect
import discord
from discord.ext import commands
import multiprocessing
app = Flask(__name__)

prefix = '%'
token = 'MyBotTokenHere'
intents = discord.Intents().all()
bot = commands.Bot(command_prefix=prefix, intents=intents)
text_channels = {}


# Discord Bot Part
async def replace_nick(id, guild_id=0):
    member2 = bot.guilds[guild_id].get_member(id)
    nick = ''
    try:
        return member2.display_name
    except AttributeError:
        return 'No Nickname'


async def clean_up_messages(messages: list):
    output = []
    for i in messages:
        nick = await replace_nick(i.author.id)
        output.append((nick, i.content))
    return output


async def get_channel1(given_id=None, guild_id=0):
    channel = discord.utils.get(bot.guilds[guild_id].channels, id=given_id)
    return channel


async def send_message1(channel: int, message, guild=0):
    channel = await get_channel1(channel, guild)
    await channel.send(message)


@bot.event
async def on_ready():
    print('Ready')
    for guild in bot.guilds:
        for channel in guild.text_channels:
            messages = await channel.history(limit=50).flatten()
            messages = await clean_up_messages(messages)
            text_channels[channel.id] = [channel.name, messages]


@bot.event
async def on_message(message: discord.Message):
    messages = await message.channel.history(limit=50).flatten()
    messages = await clean_up_messages(messages)
    text_channels[message.channel.id] = [message.channel.name, messages]


# Flask Part
@app.route('/<int:channel_id>/')
def channel(channel_id):
    global channels
    from static.bot import text_channels
    channels = text_channels.copy()
    name = channels[channel_id][0]
    mess = text_channels[channel_id][1]
    return render_template('channel.html', channel_name=name, messages=mess)


@app.route('/menu/')
def menu():
    return render_template('menu.html', channels=text_channels)


@app.route('/')
def main():
    return render_template('main.html')


if __name__ == '__main__':
    y = multiprocessing.Process(target=app.run)
    y.start()
    bot.run(token)

When I run the code, the flask app starts up and works, but the bot is offline. How do I fix this?
P.S. Answers from here don't work Running Flask & a Discord bot in the same application.

PythonSnek
  • 542
  • 4
  • 21

0 Answers0