How i can use a flask server in a plugin without blocking the BOT #326
Unanswered
Tech-User42
asked this question in
Q&A
Replies: 1 comment
-
|
Here is my plugin code import threading
from dotenv import load_dotenv
from flask import Flask, redirect, request, jsonify, render_template
import requests
from misc.const import * # Importe les constantes du fichier const.py
from misc.messages import *
import lightbulb
import hikari
import os
import sys # On importe les modules nécessaires.
import lavaplayer
from asyncio import sleep as async_wait
from misc.server_handler import check_server_status
from misc.lavalink import *
import asyncio
from lightbulb.ext import tasks
# Ajoute les sous librairies en fichier simple.
sys.path.append('/home/tech-user/MARION/MARION/marion_bot')
load_dotenv()
plugin = lightbulb.Plugin("Dashboard Handler")
def load(bot) -> None:
bot.add_plugin(plugin)
app = Flask(__name__)
@plugin.bot.listen(hikari.StartedEvent)
async def started_event(event: hikari.events.base_events.Event) -> None:
is_available = False
while(not is_available):
is_available = check_server_status('192.168.1.20',2333,timeout=1)
await async_wait(2)
print(f"{new_line(1)}[PLUGIN] Loaded plugin : {plugin.name}")
def get_user_voice_channel(user_id: int, guild_id: int):
guild_id = int(guild_id)
user_id = int(user_id)
guild = plugin.bot.cache.get_available_guild(guild_id)
if (guild == None):
return 0
voice_state = guild.get_voice_state(user_id)
if voice_state == None or voice_state.channel_id == None:
return 0
voice_channel = guild.get_channel(voice_state.channel_id)
to_return = {"id": voice_state.channel_id, "voice_channel": voice_channel}
return to_return
@app.route("/")
async def index():
return redirect(f"https://discord.com/api/oauth2/authorize?client_id={os.getenv('CLIENT_ID')}&redirect_uri={os.getenv('REDIRECT_URI')}&response_type=code&scope=guilds%20identify")
@app.route("/API/GetTrackData")
async def API_GetTrackData():
UserId = request.args.get("user_id")
GuildId = request.args.get("guild_id")
ChannelId = request.args.get("channel_id")
return jsonify(GetCurrentGuildTrack(GuildId))
@app.route("/API/InvokeBot")
async def invoke_bot():
GuildId = request.args.get("guild_id")
UserId = request.args.get("user_id")
bot = await plugin.bot.rest.fetch_member(GuildId,BOT_ID)
user = await plugin.bot.rest.fetch_member(GuildId,UserId)
UserChannelId = await user.get_guild().get_voice_state(UserId).channel_id
BotChannelId = await bot.get_guild().get_voice_state(BOT_ID).channel_id
to_return = {"is_bot_invoked": False}
if(UserChannelId != None and BotChannelId == None):
await bot.edit(voice_channel=UserChannelId)
to_return["is_bot_invoked"] = True
return jsonify(to_return)
@app.route("/dashboard")
async def dashboard():
code = request.args.get("code")
response = requests.get(f"{os.getenv('BASE_URI')}/callback?code={code}")
if response.status_code == 200:
json_data = response.json()
GuildSelectOptions = []
for guild in json_data["available_guilds"]:
GuildSelectOptions.append({'value': "{"+f'"channel_id": "{guild["channel_id"]}" , "channel_name": "{guild["channel_name"]}", "guild_id": "{guild["guild_id"]}", "guild_name": "{guild["guild_name"]}", "user_id": "{json_data["user_id"]}", "bot_connected": "{guild["bot_connected"]}"'+"}", 'text': guild["guild_name"]})
try:
return render_template("index.html", ChannelName=json_data["available_guilds"][0]["channel_name"],GuildSelectOptions=GuildSelectOptions,dump=json_data)
except IndexError:
return render_template("index.html", ChannelName="Aucun Channel Disponible",GuildSelectOptions=GuildSelectOptions,dump=json_data)
else:
return redirect(f"https://discord.com/api/oauth2/authorize?client_id={os.getenv('CLIENT_ID')}&redirect_uri={os.getenv('REDIRECT_URI')}&response_type=code&scope=guilds%20identify")
@app.route("/callback")
async def callback():
code = request.args.get("code")
payload = {
"client_id": os.getenv("CLIENT_ID"),
"client_secret": os.getenv("CLIENT_SECRET"),
"grant_type": "authorization_code",
"code": code,
"redirect_uri": os.getenv("REDIRECT_URI"),
"scope": "identify guilds"
}
headers = {
"Content-Type": "application/x-www-form-urlencoded"
}
response = requests.post(
"https://discord.com/api/oauth2/token", data=payload, headers=headers)
access_token = response.json().get("access_token")
headers = {
"Authorization": f"Bearer {access_token}"
}
response = requests.get(
"https://discord.com/api/users/@me", headers=headers)
user_data = response.json()
user_id = user_data.get("id")
response = requests.get(
"https://discord.com/api/users/@me/guilds", headers=headers)
user_guilds = response.json()
bot_token = ""
headers = {
"Authorization": f"Bot {bot_token}"
}
bot_guilds = []
for guild in plugin.bot.cache.get_available_guilds_view():
bot_guilds.append(guild)
available_guilds = []
user_voice = None
bot_voice = None
for guild in user_guilds:
try:
if(str(guild) == "message"):
continue
if (int(guild["id"]) in bot_guilds):
user_voice = await get_user_voice_channel(user_id, guild["id"])
bot_voice = await get_user_voice_channel(850383793809784852, guild["id"])
if(user_voice != 0):
available_guilds.append({
"guild_name": guild["name"],
"guild_id": guild["id"],
"channel_id": user_voice["id"],
"channel_name": user_voice["voice_channel"].name,
"bot_connected" : (bot_voice != 0)
})
# if (user_voice != 0 and bot_voice != 0):
# if (user_voice["id"] == bot_voice["id"]):
# available_guilds.append({
# "guild_name": guild["name"],
# "guild_id": guild["id"],
# "channel_id": user_voice["id"],
# "channel_name": user_voice["voice_channel"].name,
# })
except:
continue
data = {
"user_id": user_id,
"available_guilds": available_guilds
}
return jsonify(data)
threading.Thread(target=app.run(
host="192.168.1.20", port=5000, debug=True, use_reloader=False)).start()
print(f"\n[PLUGIN] Loaded plugin : {plugin.name}")
def unload(bot) -> None:
bot.remove_plugin(plugin)
print(f"\n[PLUGIN] Unloaded plugin : {plugin.name}") |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Hi,
Recently i started to make a web interface for my bot with the help of flask (i tried both sync and async flask method)
but if i run the flask app in a thread, i can't call
await plugin.bot.rest.fetch_member(GuildId,UserId)for example. because the thread don't have an event loop and when using asyncio.run it give another error about event loop.So how i can host a flask app with my bot and allow my it to use plugin and bot object like
await plugin.bot.rest.fetch_member(GuildId,UserId)?Thanks !
Beta Was this translation helpful? Give feedback.
All reactions