Spaces:
Running
on
CPU Upgrade
Running
on
CPU Upgrade
AI-powered welcoming
#4
by
ProCreations
- opened
- app.py +213 -15
- requirements.txt +3 -1
app.py
CHANGED
|
@@ -2,17 +2,44 @@ import discord
|
|
| 2 |
import os
|
| 3 |
import threading
|
| 4 |
from discord.ext import commands
|
| 5 |
-
|
| 6 |
import gradio_client
|
| 7 |
import gradio as gr
|
| 8 |
from gradio_client import Client
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
DISCORD_TOKEN = os.environ.get("DISCORD_TOKEN", None)
|
| 11 |
intents = discord.Intents.all()
|
| 12 |
bot = commands.Bot(command_prefix='!', intents=intents)
|
| 13 |
|
|
|
|
| 14 |
welcome_list = []
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
"Welcome to the community <:hugging_croissant:1103375763207622656> \n",
|
| 17 |
"Good to have you with us! :hugging: Got any cool projects you feel like sharing? :eyes: \n",
|
| 18 |
"Welcome aboard π¦ β΅ \n",
|
|
@@ -21,10 +48,96 @@ welcome_messages = [
|
|
| 21 |
"Happy to have you with us! <:blobcatlove:1103376097841790986> How much have you played around with ML/AI? :computer: \n",
|
| 22 |
"New faces, new friends! Welcome! ππ \n"
|
| 23 |
]
|
|
|
|
| 24 |
welcome_messages_counter = 0
|
| 25 |
wait_messages_counter = 0
|
| 26 |
channel_id = 900017973547388988 # 900017973547388988 = #introduce-yourself
|
| 27 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
@bot.event
|
| 29 |
async def on_member_join(member):
|
| 30 |
global welcome_list
|
|
@@ -34,7 +147,8 @@ async def on_member_join(member):
|
|
| 34 |
if len(welcome_list) >= 8:
|
| 35 |
channel = bot.get_channel(channel_id)
|
| 36 |
print(f"channel: {channel}")
|
| 37 |
-
|
|
|
|
| 38 |
count = 0
|
| 39 |
print(f"count: {count}")
|
| 40 |
async for message in channel.history(limit=3):
|
|
@@ -43,33 +157,117 @@ async def on_member_join(member):
|
|
| 43 |
else:
|
| 44 |
count = count + 1
|
| 45 |
print(f"count: {count}")
|
|
|
|
| 46 |
if count == 3:
|
| 47 |
print(f"count: {count}")
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
|
| 54 |
await channel.send(message)
|
| 55 |
welcome_list = []
|
| 56 |
-
|
| 57 |
else:
|
| 58 |
print(f"welcome_list: {welcome_list}")
|
| 59 |
|
| 60 |
-
|
| 61 |
@bot.event
|
| 62 |
async def on_message(message):
|
|
|
|
| 63 |
if message.channel.id == 900017973547388988:
|
| 64 |
await message.add_reaction('π€')
|
| 65 |
-
await bot.process_commands(message)
|
| 66 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
DISCORD_TOKEN = os.environ.get("DISCORD_TOKEN", None)
|
|
|
|
| 69 |
def run_bot():
|
| 70 |
bot.run(DISCORD_TOKEN)
|
|
|
|
|
|
|
| 71 |
threading.Thread(target=run_bot).start()
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
demo = gr.Interface(
|
| 75 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
import os
|
| 3 |
import threading
|
| 4 |
from discord.ext import commands
|
|
|
|
| 5 |
import gradio_client
|
| 6 |
import gradio as gr
|
| 7 |
from gradio_client import Client
|
| 8 |
+
import torch
|
| 9 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 10 |
+
import asyncio
|
| 11 |
+
from collections import deque
|
| 12 |
+
import re
|
| 13 |
+
import random
|
| 14 |
|
| 15 |
DISCORD_TOKEN = os.environ.get("DISCORD_TOKEN", None)
|
| 16 |
intents = discord.Intents.all()
|
| 17 |
bot = commands.Bot(command_prefix='!', intents=intents)
|
| 18 |
|
| 19 |
+
# Enhanced welcome system with AI
|
| 20 |
welcome_list = []
|
| 21 |
+
recent_introductions = deque(maxlen=15) # Store last 15 full introductions for rich context
|
| 22 |
+
model = None
|
| 23 |
+
tokenizer = None
|
| 24 |
+
|
| 25 |
+
# Initialize the AI model
|
| 26 |
+
def initialize_ai_model():
|
| 27 |
+
global model, tokenizer
|
| 28 |
+
try:
|
| 29 |
+
print("π€ Loading SmolLM2 AI model for personalized welcomes...")
|
| 30 |
+
model_id = "HuggingFaceTB/SmolLM2-360M-Instruct"
|
| 31 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
| 32 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 33 |
+
model_id,
|
| 34 |
+
torch_dtype=torch.bfloat16
|
| 35 |
+
)
|
| 36 |
+
print("β
AI model loaded successfully!")
|
| 37 |
+
except Exception as e:
|
| 38 |
+
print(f"β Failed to load AI model: {e}")
|
| 39 |
+
print("π Falling back to traditional welcome messages...")
|
| 40 |
+
|
| 41 |
+
# Fallback welcome messages (original ones)
|
| 42 |
+
fallback_welcome_messages = [
|
| 43 |
"Welcome to the community <:hugging_croissant:1103375763207622656> \n",
|
| 44 |
"Good to have you with us! :hugging: Got any cool projects you feel like sharing? :eyes: \n",
|
| 45 |
"Welcome aboard π¦ β΅ \n",
|
|
|
|
| 48 |
"Happy to have you with us! <:blobcatlove:1103376097841790986> How much have you played around with ML/AI? :computer: \n",
|
| 49 |
"New faces, new friends! Welcome! ππ \n"
|
| 50 |
]
|
| 51 |
+
|
| 52 |
welcome_messages_counter = 0
|
| 53 |
wait_messages_counter = 0
|
| 54 |
channel_id = 900017973547388988 # 900017973547388988 = #introduce-yourself
|
| 55 |
|
| 56 |
+
def store_full_introduction(message_content, author_name):
|
| 57 |
+
"""Store the complete introduction message for rich AI context"""
|
| 58 |
+
return {
|
| 59 |
+
'author': author_name,
|
| 60 |
+
'content': message_content,
|
| 61 |
+
'timestamp': discord.utils.utcnow().isoformat()
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
async def generate_ai_welcome_message(new_members, recent_context):
|
| 65 |
+
"""Generate a personalized welcome message using SmolLM2 AI with full introduction context"""
|
| 66 |
+
if not model or not tokenizer:
|
| 67 |
+
return None
|
| 68 |
+
|
| 69 |
+
try:
|
| 70 |
+
# Build rich context from recent full introductions
|
| 71 |
+
if recent_context:
|
| 72 |
+
context_intros = "\n".join([
|
| 73 |
+
f"- {intro['author']}: {intro['content'][:300]}..." if len(intro['content']) > 300
|
| 74 |
+
else f"- {intro['author']}: {intro['content']}"
|
| 75 |
+
for intro in list(recent_context)[-8:] # Use last 8 intros for context
|
| 76 |
+
])
|
| 77 |
+
else:
|
| 78 |
+
context_intros = "No recent introductions available."
|
| 79 |
+
|
| 80 |
+
# Create the AI prompt with full context
|
| 81 |
+
system_prompt = """You are a friendly, encouraging Discord community welcomer for a tech/AI community.
|
| 82 |
+
You'll be given recent introductions from community members to understand the vibe and interests.
|
| 83 |
+
|
| 84 |
+
Generate a warm, personalized welcome message that:
|
| 85 |
+
- Is enthusiastic and welcoming but not overwhelming
|
| 86 |
+
- References themes or interests you notice from recent introductions
|
| 87 |
+
- Asks an engaging question that connects to what people are discussing
|
| 88 |
+
- Uses 1-2 relevant emojis
|
| 89 |
+
- Keeps it concise (2-3 sentences max)
|
| 90 |
+
- Feels natural and conversational
|
| 91 |
+
|
| 92 |
+
DO NOT mention the new members' @ tags in your message - they will be added separately."""
|
| 93 |
+
|
| 94 |
+
user_prompt = f"""Here are recent introductions from the community:
|
| 95 |
+
|
| 96 |
+
{context_intros}
|
| 97 |
+
|
| 98 |
+
Based on these introductions, generate a welcoming message for new members joining the community. Make it feel connected to what current members are sharing and interested in."""
|
| 99 |
+
|
| 100 |
+
messages = [
|
| 101 |
+
{"role": "system", "content": system_prompt},
|
| 102 |
+
{"role": "user", "content": user_prompt},
|
| 103 |
+
]
|
| 104 |
+
|
| 105 |
+
prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 106 |
+
chat_input = tokenizer(prompt, return_tensors="pt").to(model.device)
|
| 107 |
+
|
| 108 |
+
# Generate with controlled parameters
|
| 109 |
+
with torch.no_grad():
|
| 110 |
+
chat_outputs = model.generate(
|
| 111 |
+
**chat_input,
|
| 112 |
+
max_new_tokens=100,
|
| 113 |
+
do_sample=True,
|
| 114 |
+
temperature=0.8,
|
| 115 |
+
top_p=0.9,
|
| 116 |
+
pad_token_id=tokenizer.eos_token_id
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
response = tokenizer.decode(
|
| 120 |
+
chat_outputs[0][chat_input['input_ids'].shape[-1]:],
|
| 121 |
+
skip_special_tokens=True
|
| 122 |
+
).strip()
|
| 123 |
+
|
| 124 |
+
# Clean up the response
|
| 125 |
+
response = re.sub(r'\n+', ' ', response)
|
| 126 |
+
response = response[:400] # Limit length but allow more room
|
| 127 |
+
|
| 128 |
+
return response
|
| 129 |
+
|
| 130 |
+
except Exception as e:
|
| 131 |
+
print(f"β AI generation failed: {e}")
|
| 132 |
+
return None
|
| 133 |
+
|
| 134 |
+
@bot.event
|
| 135 |
+
async def on_ready():
|
| 136 |
+
print(f'π€ {bot.user} has landed! Ready to create amazing welcomes!')
|
| 137 |
+
# Initialize AI model in background
|
| 138 |
+
loop = asyncio.get_event_loop()
|
| 139 |
+
await loop.run_in_executor(None, initialize_ai_model)
|
| 140 |
+
|
| 141 |
@bot.event
|
| 142 |
async def on_member_join(member):
|
| 143 |
global welcome_list
|
|
|
|
| 147 |
if len(welcome_list) >= 8:
|
| 148 |
channel = bot.get_channel(channel_id)
|
| 149 |
print(f"channel: {channel}")
|
| 150 |
+
|
| 151 |
+
# Check if the channel has received at least 3 messages from other users since the last bot message
|
| 152 |
count = 0
|
| 153 |
print(f"count: {count}")
|
| 154 |
async for message in channel.history(limit=3):
|
|
|
|
| 157 |
else:
|
| 158 |
count = count + 1
|
| 159 |
print(f"count: {count}")
|
| 160 |
+
|
| 161 |
if count == 3:
|
| 162 |
print(f"count: {count}")
|
| 163 |
+
|
| 164 |
+
# Try to generate AI welcome message
|
| 165 |
+
ai_message = await generate_ai_welcome_message(welcome_list[:8], list(recent_introductions))
|
| 166 |
+
|
| 167 |
+
if ai_message:
|
| 168 |
+
# Use AI-generated message
|
| 169 |
+
message = f'{ai_message} {" ".join(welcome_list[:8])}'
|
| 170 |
+
print(f"π€ Generated AI welcome: {message}")
|
| 171 |
+
else:
|
| 172 |
+
# Fallback to traditional messages
|
| 173 |
+
message = f'{fallback_welcome_messages[welcome_messages_counter]} {welcome_list[0]} {welcome_list[1]} {welcome_list[2]} {welcome_list[3]} {welcome_list[4]} {welcome_list[5]} {welcome_list[6]} {welcome_list[7]}'
|
| 174 |
+
if welcome_messages_counter == 6:
|
| 175 |
+
welcome_messages_counter = -1
|
| 176 |
+
welcome_messages_counter = welcome_messages_counter + 1
|
| 177 |
+
print(f"π Using fallback welcome message")
|
| 178 |
|
| 179 |
await channel.send(message)
|
| 180 |
welcome_list = []
|
|
|
|
| 181 |
else:
|
| 182 |
print(f"welcome_list: {welcome_list}")
|
| 183 |
|
|
|
|
| 184 |
@bot.event
|
| 185 |
async def on_message(message):
|
| 186 |
+
# React to introductions
|
| 187 |
if message.channel.id == 900017973547388988:
|
| 188 |
await message.add_reaction('π€')
|
|
|
|
| 189 |
|
| 190 |
+
# Store full introduction for rich context (if it's not from a bot and has substantial content)
|
| 191 |
+
if not message.author.bot and len(message.content) > 20:
|
| 192 |
+
full_intro = store_full_introduction(message.content, message.author.display_name)
|
| 193 |
+
recent_introductions.append(full_intro)
|
| 194 |
+
print(f"π Stored full introduction from {message.author.display_name}: {message.content[:100]}...")
|
| 195 |
+
|
| 196 |
+
await bot.process_commands(message)
|
| 197 |
+
|
| 198 |
+
# New command to test AI welcome generation
|
| 199 |
+
@bot.command(name='testwelcome')
|
| 200 |
+
async def test_welcome(ctx):
|
| 201 |
+
"""Test the AI welcome message generation (admin only)"""
|
| 202 |
+
if not ctx.author.guild_permissions.administrator:
|
| 203 |
+
await ctx.send("β Only admins can test this feature!")
|
| 204 |
+
return
|
| 205 |
+
|
| 206 |
+
# Generate a test welcome
|
| 207 |
+
test_members = [ctx.author.mention]
|
| 208 |
+
ai_message = await generate_ai_welcome_message(test_members, list(recent_introductions))
|
| 209 |
+
|
| 210 |
+
if ai_message:
|
| 211 |
+
await ctx.send(f"π€ **AI Test Welcome:**\n{ai_message}")
|
| 212 |
+
else:
|
| 213 |
+
await ctx.send("β AI generation failed, check console for errors.")
|
| 214 |
+
|
| 215 |
+
@bot.command(name='recentintros')
|
| 216 |
+
async def recent_intros(ctx):
|
| 217 |
+
"""Show recent introductions stored for AI context (admin only)"""
|
| 218 |
+
if not ctx.author.guild_permissions.administrator:
|
| 219 |
+
await ctx.send("β Only admins can view stored introductions!")
|
| 220 |
+
return
|
| 221 |
+
|
| 222 |
+
if not recent_introductions:
|
| 223 |
+
await ctx.send("π No recent introductions stored yet.")
|
| 224 |
+
return
|
| 225 |
+
|
| 226 |
+
intro_list = []
|
| 227 |
+
for i, intro in enumerate(list(recent_introductions)[-5:], 1): # Show last 5
|
| 228 |
+
preview = intro['content'][:150] + "..." if len(intro['content']) > 150 else intro['content']
|
| 229 |
+
intro_list.append(f"**{i}. {intro['author']}:** {preview}")
|
| 230 |
+
|
| 231 |
+
intros_text = "\n\n".join(intro_list)
|
| 232 |
+
await ctx.send(f"π **Recent Introductions (Last 5):**\n\n{intros_text}")
|
| 233 |
+
|
| 234 |
+
@bot.command(name='welcomestats')
|
| 235 |
+
async def welcome_stats(ctx):
|
| 236 |
+
"""Show welcome system statistics"""
|
| 237 |
+
if not ctx.author.guild_permissions.administrator:
|
| 238 |
+
await ctx.send("β Only admins can view stats!")
|
| 239 |
+
return
|
| 240 |
+
|
| 241 |
+
ai_status = "β
Loaded" if model and tokenizer else "β Not loaded"
|
| 242 |
+
intro_count = len(recent_introductions)
|
| 243 |
+
waiting_count = len(welcome_list)
|
| 244 |
+
|
| 245 |
+
stats_message = f"""π **Welcome System Stats**
|
| 246 |
+
π€ AI Model: {ai_status}
|
| 247 |
+
π Full Intros Stored: {intro_count}/15
|
| 248 |
+
β³ Members Waiting: {waiting_count}/8
|
| 249 |
+
π― Channel ID: {channel_id}"""
|
| 250 |
+
|
| 251 |
+
await ctx.send(stats_message)
|
| 252 |
+
|
| 253 |
+
# Fun gradio interface
|
| 254 |
+
def greet(name):
|
| 255 |
+
return f"Hello {name}! π The AI-powered Discord bot is running!"
|
| 256 |
|
| 257 |
DISCORD_TOKEN = os.environ.get("DISCORD_TOKEN", None)
|
| 258 |
+
|
| 259 |
def run_bot():
|
| 260 |
bot.run(DISCORD_TOKEN)
|
| 261 |
+
|
| 262 |
+
# Start bot in separate thread
|
| 263 |
threading.Thread(target=run_bot).start()
|
| 264 |
+
|
| 265 |
+
# Launch Gradio interface
|
| 266 |
+
demo = gr.Interface(
|
| 267 |
+
fn=greet,
|
| 268 |
+
inputs="text",
|
| 269 |
+
outputs="text",
|
| 270 |
+
title="π€ AI-Powered Discord Welcome Bot",
|
| 271 |
+
description="Enhanced with SmolLM2-360M-Instruct for personalized community welcomes!"
|
| 272 |
+
)
|
| 273 |
+
demo.launch()
|
requirements.txt
CHANGED
|
@@ -1,2 +1,4 @@
|
|
| 1 |
git+https://github.com/Rapptz/discord.py.git
|
| 2 |
-
gradio
|
|
|
|
|
|
|
|
|
| 1 |
git+https://github.com/Rapptz/discord.py.git
|
| 2 |
+
gradio
|
| 3 |
+
torch
|
| 4 |
+
transformers
|