0

I have a small discord bot and a small flask project (bot.py and app.py).

On my flask project I have an endpoint that I can receive JSON POST request (i can see the JSON fine). Now the question is how do I send from Flask to my Bot.py this JSON payload so that my bot.py posts it on my Discord channel.

My code:

  • flask app:
from flask import Flask, json, request,
app = Flask(__name__)


@app.route('/', methods=['GET'])
def index():
    return 'working ...'

@app.route('/webhook', methods=['POST'])
def jiraJSON():
    if request.is_json:
        data = request.get_json()
        print(data)
        return 'json received', 200
    else:
        return 'Failed - Not a JSON', 400

if __name__ == '__main__':
    app.run()
# bot.py
import os

import discord
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')

client = discord.Client()

@client.event
async def on_ready():
    print(f'{client.user} has connected to Discord!')

client.run(TOKEN)
davidism
  • 121,510
  • 29
  • 395
  • 339
  • There are packages that combine discord and flask. Maybe that works better for you. https://github.com/weibeu/Flask-Discord – Tomalak Sep 19 '21 at 07:15
  • 1
    I figured this out. I used Quart and Discord.py for my bot and it works fine. Thank you for your reply. – Bogdan Adrian Velica Sep 20 '21 at 08:45
  • 1
    Do future readers a favor and post a working sample below as an answer of your own. The number of good (and recent) samples of Quart + Discord is relatively low around here. I found a few when I was searching around, but none that I wanted to link to. – Tomalak Sep 20 '21 at 08:49
  • Good idea, will do.... – Bogdan Adrian Velica Sep 20 '21 at 08:55
  • This answer might help you ['webhook'](https://stackoverflow.com/a/63038177/13975447). It uses a webhook instead of creating a bot instance. – Abdulaziz Sep 20 '21 at 14:47

1 Answers1

1

So I've managed to make it work using Quart and a bot with Discord.py.

This will take a JSON on a webhook and send that JSON to a Discord bot to be posted on a Chanel ID.

import discord
import asyncio

from quart import Quart, request

app = Quart(__name__)
client = discord.Client()

# Setup for Discord bot
@app.before_serving
async def before_serving():
    loop = asyncio.get_event_loop()
    await client.login('<<<your_discord_bot_token_id>>>')
    loop.create_task(client.connect())

#Setup for webhook to receive POST and send it to Discord bot
@app.route('/webhook', methods=['POST'])
async def myJSON():
    channel = client.get_channel(<<<your_discord_chanel_ID>>>)
    if request.is_json:
        data = await request.get_json()
        print(data)
        await channel.send(data)
        return 'json received', 200
    else:
        return 'Failed - Not a JSON', 400


if __name__ == '__main__':
    app.run()