lunarflu's picture
lunarflu HF staff
while loop instead of native discord one + added sleeps
ae4f533 verified
raw
history blame
3.94 kB
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 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 discord.ui import Button, View
from discord.ext import commands, tasks
from datetime import datetime, timedelta
from urllib.parse import urlparse, parse_qs
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
from apscheduler.schedulers.background import BackgroundScheduler
from gspread_dataframe import get_as_dataframe, set_with_dataframe
from huggingface_hub import HfApi, list_liked_repos, list_metrics, list_models
DISCORD_TOKEN = os.environ.get("DISCORD_TOKEN", None)
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='!', intents=intents)
global_df = pd.DataFrame()
test_merge = pd.read_csv("https://docs.google.com/spreadsheets/d/1C8aLqgCqLYcMiIFf-P_Aosaa03C_WLIB_UyqvjSdWg8/export?format=csv&gid=0")
@bot.event
async def on_ready():
global global_df
"""import data from google sheets -> HF Space df (doesn't make API call this way, as it's read-only)"""
global_df = test_merge
print(f"csv successfully retrieved: \n {global_df}")
print(f"We have logged in as {bot.user}")
async def give_verified_roles():
while True:
try:
print("Starting the give_verified_roles task...")
global global_df
guild = bot.get_guild(879548962464493619)
role = guild.get_role(900063512829755413)
# Define the invite message
org_link = "https://huggingface.co/organizations/discord-community/share/wPKRAHYbAlaEaCxUxcqVyaaaeZcYagDvqc"
invite_message = "Click to join our community org on the HF Hub!"
print("Invite message and link prepared.")
# Cache members in the guild
print("Chunking guild members to cache...")
await guild.chunk()
print("Guild members chunked.")
# Iterate over the dataframe rows
for index, row in global_df.iterrows():
# Extract Hugging Face username
hf_user_name = row['hf_user_name']
if pd.notna(hf_user_name) and hf_user_name.lower() != 'n/a':
discord_id = row['discord_user_id'].strip('L')
member = guild.get_member(int(discord_id))
if not member:
continue
if role not in member.roles:
await member.add_roles(role)
print(f"Role added to member: {member}")
lunar = bot.get_user(811235357663297546)
if lunar:
await lunar.send(f"Verified role given to {member}!")
await member.send(
f"Verification successful! [{member} <---> {row['discord_user_name']}] \n🤗 {org_link} {invite_message}"
)
await asyncio.sleep(1)
print("Finished processing all rows.")
except Exception as e:
print(f"Error encountered: {e}")
await asyncio.sleep(60)
# runs discord bot in thread = helps avoid blocking calls
def run_bot():
bot.run(DISCORD_TOKEN)
threading.Thread(target=run_bot).start()
def greet(name):
return "Hello " + name + "!"
demo = gr.Interface(fn=greet, inputs="text", outputs="text")
demo.launch()