简体   繁体   English

如何知道 Flask 何时收到数据?

[英]How to know when Flask has received data?

This is a long one, so let me explain.这是一个很长的问题,所以让我解释一下。 I'm trying to write a discord bot in python using oauth2 in flask.我正在尝试在烧瓶中使用 oauth2 在 python 中编写一个不和谐的机器人。 Here is what I am trying to achieve in pseudocode: 1: user sends command in channel, 2: the bot then sends an embed with a link to the user that contains the oauth2 authorization, 3: the user clicks on the oauth2 and authorizes which gives the program their email address linked to their discord, 4: that data is then saved as a variable to be used later, and a dm is sent to the user containing their email address.这是我试图在伪代码中实现的目标:1:用户在通道中发送命令,2:机器人然后向用户发送包含 oauth2 授权的链接的嵌入,3:用户单击 oauth2 并授权哪个为程序提供与他们的不和谐相关联的电子邮件地址,4:然后将该数据保存为变量以供以后使用,并向用户发送包含其电子邮件地址的 dm。 Sounds simple.听起来很简单。

Due to discord.py being in 2.0 so I can use views and buttons and things I'm not using cogs as they were unreliable and finicky so this is all one big code.由于 discord.py 在 2.0 中,所以我可以使用视图和按钮以及我不使用 cogs 的东西,因为它们不可靠且很挑剔,所以这都是一个大代码。 I do have flask and the discord bot running on separate threads (discord bot being on 1, and flask being on 2).我确实有烧瓶和不和谐机器人在不同的线程上运行(不和谐机器人在 1 上,烧瓶在 2 上)。

#imports
import discord
from discord.ext import commands
from decouple import config
import sqlite3
from flask import Flask, request, redirect, render_template
import requests
from waitress import serve
import threading
#discord oauth things
CLIENT_ID = ''
CLIENT_SECRET = ''
REDIRECT_URI = "http://127.0.0.1:5000/success"
SCOPE = "identify%20email"
DISCORD_LOGIN = f"https://discord.com/api/oauth2/authorize?client_id={CLIENT_ID}&redirect_uri={REDIRECT_URI}&response_type=code&scope={SCOPE}&prompt=consent"
DISCORD_TOKEN = "https://discord.com/api/oauth2/token"
DISCORD_API = "https://discord.com/api"
#bot init
CLIENTTOKEN = config('CLIENTTOKEN')
class Bot(commands.Bot):
    def __init__(self):
        intents = discord.Intents.default()
        intents.message_content = True
        super().__init__(command_prefix=commands.when_mentioned_or('>'), intents=intents)
    async def on_ready(self):
        print(f'Logged in as {self.user} (ID: {self.user.id})')
        print('------')
client = Bot()
#all flask
app = Flask(__name__)
@app.route("/", methods = ["get"])
def index():
    return render_template('index.html')
@app.route("/login", methods = ["get"])
def login():
    return redirect(DISCORD_LOGIN)
@app.route("/success", methods = ["get"])
def success():
    code = request.args.get("code")
    useraccesstoken = getaccesstoken(code)
    useremail = getuseremail(useraccesstoken)
    return render_template('success.html'), useremail
def getaccesstoken(code):
    payload = {
       "client_id": CLIENT_ID,
       "client_secret": CLIENT_SECRET,
       "grant_type": "authorization_code",
       "code": code,
       "redirect_uri": REDIRECT_URI,
       "scope": SCOPE
    }
    headers = {
        "Content-Type": "application/x-www-form-urlencoded"
    }
    accesstoken = requests.post(url = DISCORD_TOKEN, data = payload, headers = headers)
    json = accesstoken.json()
    return json.get("access_token")
def getuseremail(useraccesstoken):
    url = DISCORD_API+"/users/@me"
    headers = {
        "Authorization": f"Bearer {useraccesstoken}"
    }
    userdata = requests.get(url = url, headers = headers)
    userjson = userdata.json()
    return userjson.get("email")
def web():
    serve(app, host="127.0.0.1", port=5000)
#command
@client.command()
    async def getemail(ctx):
            firstmessageembed = discord.Embed(title = "Link your Plex and your Discord", color= 
            discord.Color.from_rgb(160,131,196), description="🔗 Please click [HERE](http://127.0.0.1:5000/login) to get started.")
            firstmessageembed.set_author(name = ctx.message.author, icon_url = ctx.author.avatar.url)
            firstmessageembed.set_footer(text=f'You have 30 seconds to authorize.')
            await ctx.send(embed = firstmessageembed)
            await client.wait_for(????????????????)

threading.Thread(target=web, daemon=True).start()
client.run(CLIENTTOKEN)

As you can see I have no idea what I am waiting for and I have no idea how to know when the user has submitted the oauth2.如您所见,我不知道我在等待什么,也不知道如何知道用户何时提交了 oauth2。

I made this concept that you can try to use我提出了这个概念,你可以尝试使用

  1. Bot sends a link to the Oauth2 page Bot 发送指向 Oauth2 页面的链接
  2. Then it redirects to your web server然后它重定向到您的网络服务器
  3. On your web server JavaScript sends HTTP request to Discord API and makes a message to the user在您的 Web 服务器上,JavaScript 向 Discord API 发送 HTTP 请求并向用户发送消息

Okay so I did a lot of experimenting.好的,所以我做了很多实验。 Basically you will need to thread the discord bot and then use QUART to use await async to get the data from it.基本上,您需要线程化 discord 机器人,然后使用 QUART 使用 await async 从中获取数据。 Because there is really no way to send data between, you need to use a database, store the data that you get from Quart into the database, then just access it from the discord bot when you need to.因为确实没有办法在两者之间发送数据,所以您需要使用数据库,将您从 Quart 获取的数据存储到数据库中,然后在需要时从 discord bot 中访问它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM