Spaces:
Running
on
CPU Upgrade
Running
on
CPU Upgrade
test merge
Browse files
app.py
CHANGED
@@ -17,6 +17,8 @@ import gspread
|
|
17 |
import numpy as np
|
18 |
import pandas as pd
|
19 |
import requests
|
|
|
|
|
20 |
from apscheduler.executors.pool import ThreadPoolExecutor
|
21 |
from apscheduler.schedulers.background import BackgroundScheduler
|
22 |
from discord import Color, Embed
|
@@ -46,6 +48,7 @@ with open(file_path, 'w') as json_file:
|
|
46 |
gspread_bot = gspread.service_account(filename='service_account.json')
|
47 |
worksheet = gspread_bot.open("levelbot").sheet1
|
48 |
worksheet2 = gspread_bot.open("hf_discord_verified_users_test").sheet1
|
|
|
49 |
""""""
|
50 |
bot_ids = [1136614989411655780, 1166392942387265536, 1158038249835610123, 1130774761031610388, 1155489509518098565, 1155169841276260546, 1152238037355474964, 1154395078735953930]
|
51 |
""""""
|
@@ -57,6 +60,7 @@ worksheet2_df = pd.DataFrame()
|
|
57 |
print(type(global_df))
|
58 |
community_global_df = pd.DataFrame()
|
59 |
community_global_df_with_id = pd.DataFrame()
|
|
|
60 |
data = pd.read_csv("https://docs.google.com/spreadsheets/d/1hQSsIg1Y9WdBF_CdNM1L1rUUREoxKqRTe3_ILo-WK8w/export?format=csv&gid=0")
|
61 |
data2 = pd.read_csv("https://docs.google.com/spreadsheets/d/1T_twNONDSZ8zw7aDcYhw92DlawqPktti1xFw9ssJ13Y/export?format=csv&gid=0")
|
62 |
|
@@ -71,12 +75,9 @@ async def on_ready():
|
|
71 |
print(f"XP_PER_MESSAGE: {XP_PER_MESSAGE}")
|
72 |
|
73 |
"""import data from google sheets -> HF Space df (doesn't make API call this way, as it's read-only)"""
|
74 |
-
|
75 |
-
global_df = data
|
76 |
print(f"csv successfully retrieved: \n {global_df}")
|
77 |
|
78 |
-
|
79 |
-
|
80 |
worksheet2_df = data2.copy()
|
81 |
worksheet2_df['discord_user_id'] = worksheet2_df['discord_user_id'].astype(str)
|
82 |
worksheet2_df['id_recover_test'] = worksheet2_df['id_recover_test'].astype(str)
|
@@ -93,19 +94,15 @@ async def on_ready():
|
|
93 |
|
94 |
|
95 |
def update_google_sheet():
|
96 |
-
"""save data from HF Space -> google sheets (makes
|
97 |
try:
|
98 |
print("Updating google sheets...")
|
99 |
print(f"------------------------------------------------------------------------")
|
100 |
-
name = "
|
101 |
-
|
102 |
-
global_df['discord_user_id'] = global_df['discord_user_id'].astype(str)
|
103 |
-
global_df['discord_exp'] = global_df['discord_exp'].astype(str)
|
104 |
-
# could just do this / format
|
105 |
-
set_with_dataframe(worksheet, global_df)
|
106 |
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
107 |
print(f"------------------------------------------------------------------------")
|
108 |
-
print(f"Google sheet {name} successfully updated at {timestamp}! \n{global_df}")
|
109 |
print(f"------------------------------------------------------------------------")
|
110 |
except Exception as e:
|
111 |
print(f"update_google_sheet Error: {e}")
|
@@ -374,7 +371,7 @@ async def add_exp(member_id):
|
|
374 |
embed.set_image(url='https://cdn.discordapp.com/attachments/1150399343912833024/1205537451242688573/download_1.png?ex=65d8bb3e&is=65c6463e&hm=042fe7dd3521887db0bd48eeb846de1cc7c75194f9e95215c23512ff61ea3475&')
|
375 |
|
376 |
lunar = bot.get_user(811235357663297546)
|
377 |
-
await member.send(embed=embed)
|
378 |
await lunar.send(embed=embed)
|
379 |
print(f"Sent verification cap embed to {member}")
|
380 |
print(f"------------------------------------------------------------------------")
|
@@ -424,14 +421,14 @@ async def add_exp(member_id):
|
|
424 |
embed.add_field(name="Verify Here:", value=verification_link, inline=True)
|
425 |
|
426 |
lunar = bot.get_user(811235357663297546)
|
427 |
-
await member.send(embed=embed)
|
428 |
await lunar.send(embed=embed)
|
429 |
print(f"Sent levelup embed to {member}")
|
430 |
#You can verify your account to earn 100 points! To verify, do A.
|
431 |
|
432 |
|
433 |
print(f"------------------------------------------------------------------------")
|
434 |
-
if not member_found:
|
435 |
# if not, create new record
|
436 |
print(f"Creating new record for {member}")
|
437 |
|
@@ -444,11 +441,14 @@ async def add_exp(member_id):
|
|
444 |
if not member_id.startswith("L") and not member_id.endswith("L"):
|
445 |
member_id = f"L" + str(member_id) + f"L"
|
446 |
member_name = str(member.name)
|
447 |
-
|
448 |
hub_exp = "L0L"
|
449 |
total_exp = xp
|
450 |
-
|
451 |
-
|
|
|
|
|
|
|
452 |
print(f"------------------------------------------------------------------------")
|
453 |
except Exception as e:
|
454 |
print(f"add_exp Error: {e}")
|
@@ -456,12 +456,101 @@ async def add_exp(member_id):
|
|
456 |
|
457 |
@bot.event
|
458 |
async def on_message(message):
|
|
|
459 |
try:
|
460 |
if message.author.id not in bot_ids: # could change to if author does not have bot role (roleid)
|
461 |
-
|
462 |
-
|
463 |
-
|
464 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
465 |
await bot.process_commands(message)
|
466 |
except Exception as e:
|
467 |
print(f"on_message Error: {e}")
|
@@ -507,6 +596,7 @@ async def remove_huggingfolks():
|
|
507 |
community_global_df.drop(community_global_df.columns[1], axis=1, inplace=True)
|
508 |
community_global_df.drop(community_global_df.columns[2], axis=1, inplace=True)
|
509 |
community_global_df.drop(community_global_df.columns[2], axis=1, inplace=True)
|
|
|
510 |
community_global_df['total_exp'] = community_global_df['total_exp'].str.strip('L').astype(int)
|
511 |
community_global_df['total_exp'] = pd.to_numeric(community_global_df['total_exp'], errors='coerce').fillna(0).astype(int)
|
512 |
community_global_df = community_global_df.nlargest(len(community_global_df), 'total_exp')
|
|
|
17 |
import numpy as np
|
18 |
import pandas as pd
|
19 |
import requests
|
20 |
+
|
21 |
+
from requests import HTTPError
|
22 |
from apscheduler.executors.pool import ThreadPoolExecutor
|
23 |
from apscheduler.schedulers.background import BackgroundScheduler
|
24 |
from discord import Color, Embed
|
|
|
48 |
gspread_bot = gspread.service_account(filename='service_account.json')
|
49 |
worksheet = gspread_bot.open("levelbot").sheet1
|
50 |
worksheet2 = gspread_bot.open("hf_discord_verified_users_test").sheet1
|
51 |
+
test_merge_worksheet = gspread_bot.open("levelbot").sheet1
|
52 |
""""""
|
53 |
bot_ids = [1136614989411655780, 1166392942387265536, 1158038249835610123, 1130774761031610388, 1155489509518098565, 1155169841276260546, 1152238037355474964, 1154395078735953930]
|
54 |
""""""
|
|
|
60 |
print(type(global_df))
|
61 |
community_global_df = pd.DataFrame()
|
62 |
community_global_df_with_id = pd.DataFrame()
|
63 |
+
test_merge = pd.read_csv("https://docs.google.com/spreadsheets/d/1C8aLqgCqLYcMiIFf-P_Aosaa03C_WLIB_UyqvjSdWg8/export?format=csv&gid=0")
|
64 |
data = pd.read_csv("https://docs.google.com/spreadsheets/d/1hQSsIg1Y9WdBF_CdNM1L1rUUREoxKqRTe3_ILo-WK8w/export?format=csv&gid=0")
|
65 |
data2 = pd.read_csv("https://docs.google.com/spreadsheets/d/1T_twNONDSZ8zw7aDcYhw92DlawqPktti1xFw9ssJ13Y/export?format=csv&gid=0")
|
66 |
|
|
|
75 |
print(f"XP_PER_MESSAGE: {XP_PER_MESSAGE}")
|
76 |
|
77 |
"""import data from google sheets -> HF Space df (doesn't make API call this way, as it's read-only)"""
|
78 |
+
global_df = test_merge
|
|
|
79 |
print(f"csv successfully retrieved: \n {global_df}")
|
80 |
|
|
|
|
|
81 |
worksheet2_df = data2.copy()
|
82 |
worksheet2_df['discord_user_id'] = worksheet2_df['discord_user_id'].astype(str)
|
83 |
worksheet2_df['id_recover_test'] = worksheet2_df['id_recover_test'].astype(str)
|
|
|
94 |
|
95 |
|
96 |
def update_google_sheet():
|
97 |
+
"""save data from HF Space -> google sheets (makes 1 API call)"""
|
98 |
try:
|
99 |
print("Updating google sheets...")
|
100 |
print(f"------------------------------------------------------------------------")
|
101 |
+
name = "test_merge_worksheet"
|
102 |
+
set_with_dataframe(test_merge_worksheet, global_df)
|
|
|
|
|
|
|
|
|
103 |
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
104 |
print(f"------------------------------------------------------------------------")
|
105 |
+
print(f"Google sheet {name} {test_merge_worksheet} successfully updated at {timestamp}! \n{global_df}")
|
106 |
print(f"------------------------------------------------------------------------")
|
107 |
except Exception as e:
|
108 |
print(f"update_google_sheet Error: {e}")
|
|
|
371 |
embed.set_image(url='https://cdn.discordapp.com/attachments/1150399343912833024/1205537451242688573/download_1.png?ex=65d8bb3e&is=65c6463e&hm=042fe7dd3521887db0bd48eeb846de1cc7c75194f9e95215c23512ff61ea3475&')
|
372 |
|
373 |
lunar = bot.get_user(811235357663297546)
|
374 |
+
#await member.send(embed=embed)
|
375 |
await lunar.send(embed=embed)
|
376 |
print(f"Sent verification cap embed to {member}")
|
377 |
print(f"------------------------------------------------------------------------")
|
|
|
421 |
embed.add_field(name="Verify Here:", value=verification_link, inline=True)
|
422 |
|
423 |
lunar = bot.get_user(811235357663297546)
|
424 |
+
#await member.send(embed=embed)
|
425 |
await lunar.send(embed=embed)
|
426 |
print(f"Sent levelup embed to {member}")
|
427 |
#You can verify your account to earn 100 points! To verify, do A.
|
428 |
|
429 |
|
430 |
print(f"------------------------------------------------------------------------")
|
431 |
+
if not member_found: # this only checks if discord_user_id (with L) is present in discord_user_id column,
|
432 |
# if not, create new record
|
433 |
print(f"Creating new record for {member}")
|
434 |
|
|
|
441 |
if not member_id.startswith("L") and not member_id.endswith("L"):
|
442 |
member_id = f"L" + str(member_id) + f"L"
|
443 |
member_name = str(member.name)
|
444 |
+
hf_user_name = "n/a"
|
445 |
hub_exp = "L0L"
|
446 |
total_exp = xp
|
447 |
+
verified_date = "n/a"
|
448 |
+
|
449 |
+
row_data = [member_id, member_name, xp, current_level, hf_user_name, hub_exp, total_exp, verified_date]
|
450 |
+
global_df.loc[len(global_df.index)] = row_data
|
451 |
+
|
452 |
print(f"------------------------------------------------------------------------")
|
453 |
except Exception as e:
|
454 |
print(f"add_exp Error: {e}")
|
|
|
456 |
|
457 |
@bot.event
|
458 |
async def on_message(message):
|
459 |
+
global global_df
|
460 |
try:
|
461 |
if message.author.id not in bot_ids: # could change to if author does not have bot role (roleid)
|
462 |
+
print(f"adding exp from message {message.author}")
|
463 |
+
await asyncio.sleep(0.1)
|
464 |
+
await add_exp(message.author.id)
|
465 |
+
# add check for verification
|
466 |
+
# could add !help to bot description
|
467 |
+
|
468 |
+
if message.content.find("!help") != -1:
|
469 |
+
await message.channel.send(
|
470 |
+
"To verify your 🤗 account, message me '!auth <TOKEN>' using your API token found here: https://huggingface.co/settings/token"
|
471 |
+
)
|
472 |
+
if message.content.startswith('!auth'):
|
473 |
+
await asyncio.sleep(3)
|
474 |
+
lunar = bot.get_user(811235357663297546)
|
475 |
+
token = message.content.split()[-1].strip()
|
476 |
+
try:
|
477 |
+
user = HfApi().whoami(token)
|
478 |
+
except HTTPError as e:
|
479 |
+
await message.channel.send("Error occured when trying to authenticate. Likely invalid API Token.")
|
480 |
+
token = "abc" # reset right after we use to be safe
|
481 |
+
|
482 |
+
if user['type'] == 'org':
|
483 |
+
await message.channel.send(
|
484 |
+
"Authentication failed because you tried to authenticate with an organization's API token. Please authenticate with your User API token instead."
|
485 |
+
)
|
486 |
+
return
|
487 |
+
|
488 |
+
try:
|
489 |
+
server = bot.get_guild(879548962464493619)
|
490 |
+
#role = discord.utils.get(server.roles, name="verified")
|
491 |
+
role = server.get_role(900063512829755413)
|
492 |
+
member = server.get_member(message.author.id)
|
493 |
+
verified_date = datetime.now().strftime("%m/%d/%Y, %H:%M:%S")
|
494 |
+
# important!-----------------------------------------------------------------------------
|
495 |
+
# In order to add verification to a discord account, some important checks must ALL pass:
|
496 |
+
# 1. Discord account should not already have verified role.
|
497 |
+
# 2. hf_user_name should not already exist in the dataframe.
|
498 |
+
# -----> If it does, it means we are trying to link 1 HF account to multiple discord accounts. 1->many is disallowed.
|
499 |
+
|
500 |
+
# check if the member has the verified role (prevent duplicate entries in google sheet)
|
501 |
+
# if users want to change discord / HF accounts, we can deal with that manually
|
502 |
+
if role in member.roles:
|
503 |
+
await message.channel.send(f"{member} already has has the '{role}' role and is already verified! To change discord accounts or HF accounts, contact <@811235357663297546> or [email protected]")
|
504 |
+
return
|
505 |
+
|
506 |
+
# check if hf_user_name in dataframe:
|
507 |
+
if user['name'] in global_df['hf_user_name'].values:
|
508 |
+
await message.channel.send(f"The HF account {user['name']} is already verified! To change discord accounts or HF accounts, contact <@811235357663297546> or [email protected]")
|
509 |
+
return
|
510 |
+
|
511 |
+
# check if discord_user_id in dataframe:
|
512 |
+
altered_member_id = "L" + str(member.id) + "L"
|
513 |
+
if altered_member_id in global_df['discord_user_id'].values:
|
514 |
+
|
515 |
+
hf_user_name = global_df.loc[global_df['discord_user_id'] == altered_member_id, 'hf_user_name'].iloc[0]
|
516 |
+
|
517 |
+
if hf_user_name == 'n/a':
|
518 |
+
# empty (no link created yet between discord_user_id and hf_user_name) so we can update
|
519 |
+
global_df.loc[global_df['discord_user_id'] == altered_member_id, 'hf_user_name'] = user['name']
|
520 |
+
global_df.loc[global_df['discord_user_id'] == altered_member_id, 'verified_date'] = verified_date
|
521 |
+
print(f"Updated hf_user_name for id {member.id} | discord_user_name {member} | hf_user_name {user['name']}")
|
522 |
+
await message.channel.send(f"Verification successful! [{member} <---> {user['name']}] 🤗")
|
523 |
+
await lunar.send(f"Verification successful! [{member} <---> {user['name']}] 🤗")
|
524 |
+
print(f"Verification successful! [{member} <---> {user['name']}] 🤗")
|
525 |
+
return
|
526 |
+
else:
|
527 |
+
await message.channel.send(f"The Discord account {member} is already verified! To change discord accounts or HF accounts, contact <@811235357663297546> or [email protected]")
|
528 |
+
await lunar.send(f"The Discord account {member} is already verified! To change discord accounts or HF accounts, contact <@811235357663297546> or [email protected]")
|
529 |
+
print(f"The Discord account {member} is already verified! To change discord accounts or HF accounts, contact <@811235357663297546> or [email protected]")
|
530 |
+
return
|
531 |
+
|
532 |
+
# -----------------------------------------------------------------------------------------
|
533 |
+
xp = 10
|
534 |
+
current_level = calculate_level(xp)
|
535 |
+
xp = str(xp)
|
536 |
+
if not xp.startswith("L") and not xp.endswith("L"):
|
537 |
+
xp = f"L" + str(xp) + f"L"
|
538 |
+
hub_exp = "L0L"
|
539 |
+
total_exp = xp
|
540 |
+
|
541 |
+
row_data = [altered_member_id,
|
542 |
+
member.name,
|
543 |
+
xp,
|
544 |
+
current_level,
|
545 |
+
user['name'],
|
546 |
+
"L0L",
|
547 |
+
xp,
|
548 |
+
verified_date]
|
549 |
+
|
550 |
+
global_df.loc[len(global_df.index)] = row_data
|
551 |
+
await member.add_roles(role)
|
552 |
+
print(f"New record created for ")
|
553 |
+
|
554 |
await bot.process_commands(message)
|
555 |
except Exception as e:
|
556 |
print(f"on_message Error: {e}")
|
|
|
596 |
community_global_df.drop(community_global_df.columns[1], axis=1, inplace=True)
|
597 |
community_global_df.drop(community_global_df.columns[2], axis=1, inplace=True)
|
598 |
community_global_df.drop(community_global_df.columns[2], axis=1, inplace=True)
|
599 |
+
community_global_df.drop(community_global_df.columns[3], axis=1, inplace=True)
|
600 |
community_global_df['total_exp'] = community_global_df['total_exp'].str.strip('L').astype(int)
|
601 |
community_global_df['total_exp'] = pd.to_numeric(community_global_df['total_exp'], errors='coerce').fillna(0).astype(int)
|
602 |
community_global_df = community_global_df.nlargest(len(community_global_df), 'total_exp')
|