Spaces:
Sleeping
Sleeping
Create main.py
Browse files
main.py
ADDED
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import asyncio
|
3 |
+
from fastapi import FastAPI
|
4 |
+
from discord.ext import commands
|
5 |
+
from dotenv import load_dotenv
|
6 |
+
import discord
|
7 |
+
import aiohttp
|
8 |
+
import io
|
9 |
+
load_dotenv()
|
10 |
+
|
11 |
+
WELCOME_IMAGE_API = os.getenv("WELCOME_IMAGE_API")
|
12 |
+
WELCOME_CHANNEL_ID = int(os.getenv("WELCOME_CHANNEL_ID"))
|
13 |
+
DISCORD_BOT_TOKEN = os.getenv("DISCORD_BOT_TOKEN")
|
14 |
+
|
15 |
+
|
16 |
+
intents = discord.Intents.default()
|
17 |
+
intents.members = True
|
18 |
+
|
19 |
+
bot = commands.Bot(command_prefix="!", intents=intents)
|
20 |
+
|
21 |
+
app = FastAPI()
|
22 |
+
|
23 |
+
|
24 |
+
app = FastAPI()
|
25 |
+
@app.on_event("startup")
|
26 |
+
async def startup_event():
|
27 |
+
asyncio.create_task(bot.start(DISCORD_BOT_TOKEN))
|
28 |
+
|
29 |
+
@app.on_event("shutdown")
|
30 |
+
async def shutdown_event():
|
31 |
+
await bot.close()
|
32 |
+
|
33 |
+
@bot.event
|
34 |
+
async def on_ready():
|
35 |
+
print(f"π€ Logged in as {bot.user}")
|
36 |
+
|
37 |
+
@bot.event
|
38 |
+
async def on_member_join(member):
|
39 |
+
username = member.name
|
40 |
+
avatar_url = member.display_avatar.replace(format="png", size=256).url
|
41 |
+
user_id = member.id
|
42 |
+
|
43 |
+
print(f"π€ New member: {username} ({user_id})")
|
44 |
+
|
45 |
+
try:
|
46 |
+
async with aiohttp.ClientSession() as session:
|
47 |
+
async with session.post(WELCOME_IMAGE_API, json={
|
48 |
+
"username": username,
|
49 |
+
"avatar_url": avatar_url
|
50 |
+
}) as resp:
|
51 |
+
if resp.status != 200:
|
52 |
+
print("β Image generation failed")
|
53 |
+
return
|
54 |
+
|
55 |
+
image_data = await resp.read()
|
56 |
+
|
57 |
+
channel = bot.get_channel(WELCOME_CHANNEL_ID)
|
58 |
+
if channel is None:
|
59 |
+
print("β Channel not found")
|
60 |
+
return
|
61 |
+
|
62 |
+
file = discord.File(fp=io.BytesIO(image_data), filename=f"welcome-{username}.png")
|
63 |
+
|
64 |
+
await channel.send(
|
65 |
+
content=f"Explore, learn, and automate smarter β welcome to the AI Automation Club, <@{user_id}>!",
|
66 |
+
file=file
|
67 |
+
)
|
68 |
+
|
69 |
+
print(f"β
Welcome message sent to channel for {username}")
|
70 |
+
except Exception as e:
|
71 |
+
print(f"β Error in welcome process: {e}")
|
72 |
+
|
73 |
+
|
74 |
+
@app.get("/")
|
75 |
+
async def root():
|
76 |
+
return {"message": "FastAPI is running with the Discord bot"}
|