lunarflu HF staff commited on
Commit
8681a0b
·
verified ·
1 Parent(s): 39d3eff
Files changed (1) hide show
  1. app.py +86 -108
app.py CHANGED
@@ -1,148 +1,126 @@
1
  import os
2
  import io
 
 
3
  import sys
 
 
 
4
  import asyncio
5
  import discord
 
6
  import aiohttp
 
 
 
 
 
 
 
 
7
  import pandas as pd
8
  import gradio as gr
9
- import logging
10
- from discord.ext import commands
11
-
12
- # Set up logging
13
- logging.basicConfig(
14
- level=logging.INFO,
15
- format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
16
- datefmt="%Y-%m-%d %H:%M:%S"
17
- )
18
- logger = logging.getLogger(__name__)
 
 
 
 
19
 
20
  DISCORD_TOKEN = os.environ.get("DISCORD_TOKEN", None)
21
- if not DISCORD_TOKEN:
22
- logger.error("DISCORD_TOKEN not set. Exiting.")
23
- sys.exit(1)
24
-
25
- intents = discord.Intents.all()
26
- bot = commands.Bot(command_prefix="!", intents=intents)
27
-
28
- # Cache guild/role globally
29
- GUILD_ID = 879548962464493619
30
- ROLE_ID = 900063512829755413
31
- LUNAR_ID = 811235357663297546
32
-
33
- async def process_row(row, guild, role):
34
- hf_user_name = row["hf_user_name"]
35
- if pd.notna(hf_user_name) and hf_user_name.lower() != "n/a":
36
- discord_id = row["discord_user_id"].strip("L")
37
- try:
38
- member = guild.get_member(int(discord_id))
39
- except Exception as e:
40
- logger.error(f"Error converting Discord ID {discord_id}: {e}")
41
- return
42
-
43
- if not member:
44
- return
45
-
46
- if role not in member.roles:
47
- try:
48
- await member.add_roles(role)
49
- logger.info(f"Role added to member: {member}")
50
-
51
- # Send confirmation to Lunar (optional)
52
- lunar = bot.get_user(LUNAR_ID)
53
- if lunar:
54
- try:
55
- await lunar.send(f"Verified role given to {member}!")
56
- except discord.Forbidden:
57
- logger.warning("Could not DM Lunar.")
58
-
59
- # DM the user (optional)
60
- try:
61
- await member.send(
62
- f"Verification successful! [{member} <---> {row['discord_user_name']}]"
63
- )
64
- except discord.Forbidden:
65
- logger.warning(f"Cannot DM {member} — DMs likely off.")
66
 
67
- except Exception as e:
68
- logger.error(f"Error processing member {member}: {e}")
69
 
70
- async def give_verified_roles():
71
- guild = bot.get_guild(GUILD_ID)
72
- role = guild.get_role(ROLE_ID)
 
 
73
 
74
- if not guild or not role:
75
- logger.error("Guild or role not found. Exiting loop.")
76
- return
 
 
 
 
 
 
 
 
77
 
 
78
  while True:
79
  try:
 
 
80
  async with aiohttp.ClientSession() as session:
81
  try:
82
  async with session.get(
83
  "https://docs.google.com/spreadsheets/d/1C8aLqgCqLYcMiIFf-P_Aosaa03C_WLIB_UyqvjSdWg8/export?format=csv&gid=0",
84
- timeout=10,
85
  ) as response:
86
  if response.status != 200:
87
- logger.error(f"Failed to fetch CSV: HTTP {response.status}")
88
  await asyncio.sleep(30)
89
  continue
90
-
91
  csv_data = await response.text()
92
- global_df = await asyncio.to_thread(pd.read_csv, io.StringIO(csv_data))
93
-
94
  except asyncio.TimeoutError:
95
- logger.error("CSV fetch timed out.")
96
  await asyncio.sleep(30)
97
  continue
98
  except Exception as e:
99
- logger.error(f"Error fetching CSV: {e}")
100
  await asyncio.sleep(30)
101
  continue
102
 
103
- # Throttled loop to avoid hitting rate limits
104
- for _, row in global_df.iterrows():
105
- await process_row(row, guild, role)
106
- await asyncio.sleep(1.5) # Delay between role assignments
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
 
108
  except Exception as e:
109
- logger.error(f"Error in give_verified_roles loop: {e}")
 
110
 
111
- await asyncio.sleep(30)
 
112
 
113
- @bot.event
114
- async def on_ready():
115
- logger.info(f"We have logged in as {bot.user}")
116
- guild = bot.get_guild(GUILD_ID)
117
- if guild:
118
- await guild.chunk() # Cache members once on ready
119
- logger.info("Guild member cache initialized.")
120
- else:
121
- logger.warning("Guild not found on startup.")
122
-
123
- bot.loop.create_task(give_verified_roles())
124
- bot.loop.create_task(heartbeat())
125
-
126
- async def heartbeat():
127
- while True:
128
- logger.info("Heartbeat: Bot is active.")
129
- await asyncio.sleep(60)
130
 
131
- # Gradio setup
132
  def greet(name):
133
  return "Hello " + name + "!"
134
-
135
  demo = gr.Interface(fn=greet, inputs="text", outputs="text")
136
-
137
- async def main():
138
- gradio_thread = asyncio.to_thread(demo.launch, share=False)
139
- await asyncio.gather(
140
- bot.start(DISCORD_TOKEN),
141
- gradio_thread
142
- )
143
-
144
- if __name__ == "__main__":
145
- try:
146
- asyncio.run(main())
147
- except KeyboardInterrupt:
148
- logger.info("Shutting down...")
 
1
  import os
2
  import io
3
+ import re
4
+ import csv
5
  import sys
6
+ import json
7
+ import time
8
+ import random
9
  import asyncio
10
  import discord
11
+ import logging
12
  import aiohttp
13
+ import gspread
14
+ import datetime
15
+ import requests
16
+ import threading
17
+ import schedule
18
+ import gradio_client
19
+
20
+ import numpy as np
21
  import pandas as pd
22
  import gradio as gr
23
+ import plotly.graph_objects as go
24
+
25
+ from tabulate import tabulate
26
+ from requests import HTTPError
27
+ from gradio_client import Client
28
+ from discord import Color, Embed
29
+ from discord.ui import Button, View
30
+ from discord.ext import commands, tasks
31
+ from datetime import datetime, timedelta
32
+ from urllib.parse import urlparse, parse_qs
33
+ from apscheduler.schedulers.asyncio import AsyncIOScheduler
34
+ from gspread_formatting.dataframe import format_with_dataframe
35
+ from gspread_dataframe import get_as_dataframe, set_with_dataframe
36
+ from huggingface_hub import HfApi, list_liked_repos, list_models
37
 
38
  DISCORD_TOKEN = os.environ.get("DISCORD_TOKEN", None)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
+ intents = discord.Intents.all()
41
+ bot = commands.Bot(command_prefix='!', intents=intents)
42
 
43
+ scheduler = AsyncIOScheduler()
44
+
45
+ def restart_bot():
46
+ print("Restarting bot...")
47
+ os.execv(sys.executable, ['python'] + sys.argv)
48
 
49
+ @scheduler.scheduled_job('interval', minutes=60)
50
+ def periodic_restart():
51
+ print("Scheduled restart triggered...")
52
+ restart_bot()
53
+
54
+ @bot.event
55
+ async def on_ready():
56
+ """Import data from Google Sheets -> HF Space df"""
57
+ print(f"We have logged in as {bot.user}")
58
+ scheduler.start()
59
+ await give_verified_roles()
60
 
61
+ async def give_verified_roles():
62
  while True:
63
  try:
64
+ global_df = pd.DataFrame()
65
+
66
  async with aiohttp.ClientSession() as session:
67
  try:
68
  async with session.get(
69
  "https://docs.google.com/spreadsheets/d/1C8aLqgCqLYcMiIFf-P_Aosaa03C_WLIB_UyqvjSdWg8/export?format=csv&gid=0",
70
+ timeout=10
71
  ) as response:
72
  if response.status != 200:
73
+ print(f"Failed to fetch CSV: HTTP {response.status}")
74
  await asyncio.sleep(30)
75
  continue
 
76
  csv_data = await response.text()
77
+ global_df = pd.read_csv(io.StringIO(csv_data))
 
78
  except asyncio.TimeoutError:
79
+ print("CSV fetch timed out.")
80
  await asyncio.sleep(30)
81
  continue
82
  except Exception as e:
83
+ print(f"Error fetching CSV: {e}")
84
  await asyncio.sleep(30)
85
  continue
86
 
87
+ guild = bot.get_guild(879548962464493619)
88
+ role = guild.get_role(900063512829755413)
89
+
90
+ org_link = "https://huggingface.co/organizations/discord-community/share/wPKRAHYbAlaEaCxUxcqVyaaaeZcYagDvqc"
91
+ invite_message = "Click to join our community org on the HF Hub!"
92
+
93
+ await guild.chunk()
94
+
95
+ for index, row in global_df.iterrows():
96
+ hf_user_name = row['hf_user_name']
97
+ if pd.notna(hf_user_name) and hf_user_name.lower() != 'n/a':
98
+ discord_id = row['discord_user_id'].strip('L')
99
+ member = guild.get_member(int(discord_id))
100
+ if not member:
101
+ continue
102
+ if role not in member.roles:
103
+ await member.add_roles(role)
104
+ #await asyncio.sleep(1)
105
+ print(f"Role added to member: {member}")
106
+ lunar = bot.get_user(811235357663297546)
107
+ if lunar:
108
+ await lunar.send(f"Verified role given to {member}!")
109
+ await member.send(
110
+ f"Verification successful! [{member} <---> {row['discord_user_name']}] \n🤗 {org_link} {invite_message}"
111
+ )
112
+ #await asyncio.sleep(1)
113
 
114
  except Exception as e:
115
+ print(f"Error encountered: {e}")
116
+ await asyncio.sleep(10) # 30
117
 
118
+ def run_bot():
119
+ bot.run(DISCORD_TOKEN)
120
 
121
+ threading.Thread(target=run_bot).start()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
 
 
123
  def greet(name):
124
  return "Hello " + name + "!"
 
125
  demo = gr.Interface(fn=greet, inputs="text", outputs="text")
126
+ demo.launch()