lunarflu HF staff commited on
Commit
d522acf
·
verified ·
1 Parent(s): 7b154b2

reset every 20min

Browse files
Files changed (1) hide show
  1. app.py +12 -69
app.py CHANGED
@@ -9,14 +9,12 @@ import random
9
  import asyncio
10
  import discord
11
  import logging
12
- import os.path
13
- import secrets
14
  import aiohttp
15
  import gspread
16
  import datetime
17
- import schedule
18
  import requests
19
  import threading
 
20
  import gradio_client
21
 
22
  import numpy as np
@@ -32,33 +30,34 @@ from discord.ui import Button, View
32
  from discord.ext import commands, tasks
33
  from datetime import datetime, timedelta
34
  from urllib.parse import urlparse, parse_qs
35
- from apscheduler.executors.pool import ThreadPoolExecutor
36
- from apscheduler.executors.asyncio import AsyncIOExecutor
37
  from apscheduler.schedulers.asyncio import AsyncIOScheduler
38
  from gspread_formatting.dataframe import format_with_dataframe
39
- from apscheduler.schedulers.background import BackgroundScheduler
40
  from gspread_dataframe import get_as_dataframe, set_with_dataframe
41
  from huggingface_hub import HfApi, list_liked_repos, list_models
42
 
43
-
44
  DISCORD_TOKEN = os.environ.get("DISCORD_TOKEN", None)
 
45
  intents = discord.Intents.all()
46
  bot = commands.Bot(command_prefix='!', intents=intents)
47
 
 
48
 
49
- ## testing restart
50
  def restart_bot():
51
  print("Restarting bot...")
52
  os.execv(sys.executable, ['python'] + sys.argv)
53
 
 
 
 
 
54
 
55
  @bot.event
56
  async def on_ready():
57
- """import data from google sheets -> HF Space df (doesn't make API call this way, as it's read-only)"""
58
  print(f"We have logged in as {bot.user}")
 
59
  await give_verified_roles()
60
 
61
-
62
  async def give_verified_roles():
63
  while True:
64
  try:
@@ -84,65 +83,9 @@ async def give_verified_roles():
84
  print(f"Error fetching CSV: {e}")
85
  await asyncio.sleep(60)
86
  continue
87
-
88
  guild = bot.get_guild(879548962464493619)
89
  role = guild.get_role(900063512829755413)
90
-
91
- # Define the invite message
92
- org_link = "https://huggingface.co/organizations/discord-community/share/wPKRAHYbAlaEaCxUxcqVyaaaeZcYagDvqc"
93
- invite_message = "Click to join our community org on the HF Hub!"
94
-
95
- # Cache members in the guild
96
- await guild.chunk()
97
-
98
- # Iterate over the dataframe rows
99
- for index, row in global_df.iterrows():
100
- # Extract Hugging Face username
101
- hf_user_name = row['hf_user_name']
102
- if pd.notna(hf_user_name) and hf_user_name.lower() != 'n/a':
103
- discord_id = row['discord_user_id'].strip('L')
104
- member = guild.get_member(int(discord_id))
105
- if not member:
106
- continue
107
- if role not in member.roles:
108
- await member.add_roles(role)
109
- await asyncio.sleep(5)
110
- print(f"Role added to member: {member}")
111
- #await asyncio.sleep(10)
112
- lunar = bot.get_user(811235357663297546)
113
- if lunar:
114
- await lunar.send(f"Verified role given to {member}!")
115
- await member.send(
116
- f"Verification successful! [{member} <---> {row['discord_user_name']}] \n🤗 {org_link} {invite_message}"
117
- )
118
- await asyncio.sleep(5)
119
-
120
- except Exception as e:
121
- print(f"Error encountered: {e}")
122
- await asyncio.sleep(30) # was 60
123
-
124
-
125
- # Function to run the bot in a thread
126
- def run_bot():
127
- bot.run(DISCORD_TOKEN)
128
 
129
-
130
- # Function to schedule the bot restart at midnight
131
- def schedule_restart():
132
- schedule.every().day.at("00:00").do(restart_bot)
133
-
134
- while True:
135
- schedule.run_pending()
136
- time.sleep(1)
137
-
138
-
139
- # Launch the bot and restart scheduler in separate threads
140
- threading.Thread(target=run_bot).start()
141
- threading.Thread(target=schedule_restart).start()
142
-
143
-
144
- # Example Gradio interface
145
- def greet(name):
146
- return "Hello " + name + "!"
147
- demo = gr.Interface(fn=greet, inputs="text", outputs="text")
148
- demo.launch()
 
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
 
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=20)
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:
 
83
  print(f"Error fetching CSV: {e}")
84
  await asyncio.sleep(60)
85
  continue
86
+
87
  guild = bot.get_guild(879548962464493619)
88
  role = guild.get_role(900063512829755413)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
 
90
+ # Define the invite message
91
+ org_link = "https://huggingface.co/organizations/discord-community/share/wPKRAHYbAlaEaCxUxcq