Spaces:
Running
on
CPU Upgrade
Running
on
CPU Upgrade
File size: 6,739 Bytes
5a26019 65c7e49 8b23687 5a26019 65c7e49 5086fc0 5a26019 39a3bfb 5a26019 8b23687 65c7e49 5a26019 65c7e49 bfb4d01 5a26019 4d6295e 6386d92 5a26019 6386d92 5a26019 8b23687 fc1881a 5a26019 7586254 5a26019 42d451d 39a3bfb 5a26019 500d61b c284eb8 65c7e49 421347b a5603d3 7187a61 cf1e692 a5603d3 5a26019 d520393 e91740b 39a3bfb 0aa83ad d0b459f 5a26019 4e807ea 5a26019 6b5ae25 f5d5dc6 eb0e82f e698139 963edf4 5a26019 963edf4 5a26019 963edf4 5a26019 e698139 0b7628c 4f19e81 4e807ea 0b7628c 66cef69 d0b459f 66cef69 459c6ce 4e807ea d0b459f 4e807ea 4f0ae67 bfb3bca 22d3c95 f5d5dc6 f5010c4 f5d5dc6 5a26019 359b637 42641d6 f5d5dc6 63e32ce ca772d6 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 |
import os
import re
import csv
import json
import time
import random
import asyncio
import discord
import logging
import os.path
import secrets
import gspread
import datetime
import tempfile
import requests
import threading
import gradio_client
import numpy as np
import pandas as pd
import gradio as gr
import plotly.graph_objects as go
from tabulate import tabulate
from requests import HTTPError
from gradio_client import Client
from discord import Color, Embed
from huggingface_hub import HfApi
from discord.ui import Button, View
from discord.ext import commands, tasks
from datetime import datetime, timedelta
from urllib.parse import urlparse, parse_qs
# starting to migrate to HF datasets and away from google sheets
from huggingface_hub import HfApi, HfFolder, Repository
from apscheduler.executors.pool import ThreadPoolExecutor
from apscheduler.executors.asyncio import AsyncIOExecutor
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from gspread_formatting.dataframe import format_with_dataframe
DISCORD_TOKEN = os.environ.get("DISCORD_TOKEN", None)
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='!', intents=intents)
GRADIO_APP_URL = "https://huggingface.co/spaces/discord-community/LevelBot"
""""""
bot_ids = [1136614989411655780, 1166392942387265536, 1158038249835610123, 1130774761031610388, 1155489509518098565, 1155169841276260546, 1152238037355474964, 1154395078735953930]
""""""
hf_token = os.environ.get("HF_TOKEN")
discord_loop = None # global variable
class DMButton(Button):
def __init__(self, label, style):
super().__init__(label=label, style=style)
async def callback(self, interaction: discord.Interaction):
# await interaction.user.send(self.message) # this is for DMs, but users may have DMs disabled
user_id = interaction.user.id
guild = interaction.guild
member = guild.get_member(user_id)
pending_role = guild.get_role(1380908157475360899) # pending verification role, this is to verify that the discord account actually clicked the button at least once
if member and pending_role:
await member.add_roles(pending_role)
print(f"Assigned 'Pending Verification' role to {member.name}") # should log this in #admin-logs properly
unique_link = f"<{GRADIO_APP_URL}?user_id={user_id}>" # don't need token
message = f"Login link generated! To complete the verification process:\n- 1 Visit this link,\n- 2 click the 'π€Sign in with Hugging Face' button\n\n{unique_link}"
await interaction.response.send_message(message, ephemeral=True)
@bot.event
async def on_ready():
try:
print(f'Logged in as {bot.user.name}')
guild = bot.get_guild(879548962464493619)
await guild.chunk() # get all users into bot cache
channel = bot.get_channel(900125909984624713)
if channel:
try:
message = await channel.fetch_message(1271145797433557023)
if message:
button = DMButton(label="Verify Discord Account", style=discord.ButtonStyle.primary)
view = View(timeout=None)
view.add_item(button)
await message.edit(view=view)
print("message edited")
except discord.NotFound:
print(f"Message with ID 1271145797433557023 not found.")
except discord.HTTPException as e:
print(f"Failed to fetch message with ID 1271145797433557023: {e}")
print("------------------------------------------------------------------------")
except Exception as e:
print(f"on_ready Error: {e}")
DISCORD_TOKEN = os.environ.get("DISCORD_TOKEN", None)
def run_bot():
global discord_loop
discord_loop = asyncio.new_event_loop()
asyncio.set_event_loop(discord_loop)
discord_loop.create_task(bot.start(DISCORD_TOKEN))
discord_loop.run_forever()
threading.Thread(target=run_bot).start()
def verify_button(profile: gr.OAuthProfile | None, request: gr.Request) -> str:
query_params = parse_qs(urlparse(str(request.url)).query)
user_id = query_params.get('user_id', [None])[0]
if not user_id:
return "# β Missing Discord user ID."
if profile is None:
return "# β You're not logged in with Hugging Face."
async def upgrade_role():
guild = bot.get_guild(879548962464493619)
member = guild.get_member(int(user_id))
pending_role = guild.get_role(1380908157475360899) # pending
verified_role = guild.get_role(900063512829755413) # verified
if not member:
print(f"β Could not find Discord user {user_id}")
return
if pending_role in member.roles:
await member.remove_roles(pending_role)
await member.add_roles(verified_role)
print(f"β
{member.name} verified and upgraded to verified role.")
else:
print(f"β οΈ {member.name} did not have the pending role. Ignoring.")
global discord_loop
if discord_loop:
asyncio.run_coroutine_threadsafe(upgrade_role(), discord_loop)
return f"# β
Verification successful! Welcome, {profile.username} π"
demo = gr.Blocks()
with demo:
try:
TITLE = """<h1 align="center" id="space-title">π€ Hugging Face Discord Verification</h1>"""
gr.HTML(TITLE)
with gr.Tabs(elem_classes="tab-buttons") as tabs:
#------------------------------------------------------------------------------
with gr.TabItem("β
Discord Verification", elem_id="verify-tab", id=2):
login_button = gr.LoginButton()
m1 = gr.Markdown()
demo.load(verify_button, inputs=None, outputs=m1)
def check_login_status():
try:
return login_button.get_session().get("oauth_info", None)
except AttributeError:
return None
def check_login_wrapper():
session = check_login_status()
if session is None:
return "Not logged in."
else:
return f"Logged in as {session.get('username', 'Unknown')}"
login_button.click(check_login_wrapper, inputs=None, outputs=m1)
#------------------------------------------------------------------------------
#with gr.TabItem("π Hub-only leaderboard", elem_id="hub-table", id=2):
except Exception as e:
print(f"gradio demo Error: {e}")
demo.queue().launch() |