lunarflu HF staff commited on
Commit
297c8cc
1 Parent(s): dfa5be9

retry (set_with_dataframe(worksheet, global_df) )

Browse files
Files changed (1) hide show
  1. app.py +85 -188
app.py CHANGED
@@ -15,11 +15,11 @@ from tabulate import tabulate
15
  import logging
16
  import time
17
  import pandas as pd
 
18
  from gspread_dataframe import get_as_dataframe, set_with_dataframe
19
  from gspread_formatting.dataframe import format_with_dataframe
20
  import numpy as np
21
 
22
-
23
  import gradio_client
24
  import gradio as gr
25
  from gradio_client import Client
@@ -48,12 +48,38 @@ bot_ids = [1136614989411655780, 1166392942387265536, 1158038249835610123, 113077
48
  """"""
49
  api = HfApi()
50
  """"""
51
-
 
52
 
53
  @bot.event
54
  async def on_ready():
 
55
  print(f'Logged in as {bot.user.name}')
56
  print(f"XP_PER_MESSAGE: {XP_PER_MESSAGE}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
 
58
 
59
  def calculate_level(xp):
@@ -66,7 +92,7 @@ def calculate_xp(level):
66
 
67
  processed_users = set()
68
 
69
- async def periodic_api_test():
70
  try:
71
  await asyncio.sleep(1)
72
  column_values_3 = worksheet2.col_values(3)
@@ -98,59 +124,12 @@ async def periodic_api_test():
98
  print(f"Failed to retrieve data for user {user}. Status code: {response.status_code}")
99
 
100
  except Exception as e:
101
- print(f"periodic_api_test Error: {e}")
102
-
103
-
104
- def blocking_io(member_id):
105
- try:
106
- time.sleep(1)
107
- worksheet = gspread_bot.open("levelbot").sheet1
108
-
109
- guild = bot.get_guild(879548962464493619)
110
- member = guild.get_member(member_id)
111
- print(f" {member}")
112
- print(f"2")
113
-
114
- cell = worksheet.find(str(member.id))
115
- length = len(worksheet.col_values(1))
116
- print(f"3")
117
- if cell is None:
118
- print(f"creating new record for {member}")
119
- # if not, create new record
120
- string_member_id = str(member.id)
121
- xp = 10
122
- current_level = calculate_level(xp)
123
- member_name = member.name
124
- worksheet.update(values=[[string_member_id, member_name, xp, current_level]], range_name=f'A{length+1}:D{length+1}')
125
- # initial role assignment
126
- if current_level == 1:
127
- if lvl1 not in member.roles:
128
- return(1)
129
-
130
- else:
131
- print(f"4")
132
- if cell:
133
- # if so, update that row...
134
- xp = worksheet.cell(cell.row, cell.col+2).value
135
- xp = int(xp) + XP_PER_MESSAGE
136
- current_level = calculate_level(xp)
137
- print(f"updating record for {member}: {xp} xp")
138
- # write with added xp
139
- worksheet.update(values=[[xp, current_level]], range_name=f'C{cell.row}:D{cell.row}')
140
- # level up
141
- print(f"current_level: {current_level}")
142
- if current_level >= 2 and current_level <=30:
143
- # pass current_level as int?
144
- return(current_level)
145
- except Exception as e:
146
- print(f"blocking_io Error: {e}")
147
 
148
 
149
  async def add_exp(member_id):
150
  try:
151
- await asyncio.sleep(1)
152
- loop = asyncio.get_running_loop()
153
- result = await loop.run_in_executor(None, blocking_io, member_id)
154
 
155
  guild = bot.get_guild(879548962464493619)
156
  member = guild.get_member(member_id)
@@ -192,24 +171,54 @@ async def add_exp(member_id):
192
  21: lvl21, 22: lvl22, 23: lvl23, 24: lvl24, 25: lvl25, 26: lvl26, 27: lvl27, 28: lvl28, 29: lvl29, 30: lvl30,
193
  }
194
 
195
- if result == 1:
196
- await member.add_roles(lvl1)
197
- print(f"Gave {member} {lvl1}")
198
-
199
- print(f"result: {result}")
200
- if result >= 2:
201
- current_level = result
202
- current_role = lvls[current_level]
203
- if current_role not in member.roles:
204
- await member.add_roles(current_role)
205
- print(f"Giving {member} {current_role}")
206
- await member.remove_roles(lvls[current_level-1])
207
- print(f"Removed {lvls[current_level-1]} from {member}")
208
- #print(f"{member} Level up! {current_level-1} -> {current_level}!")
209
- if current_role in member.roles:
210
- await member.send(f"Level up! {current_level-1} -> {current_level}!")
211
-
212
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
213
  except Exception as e:
214
  print(f"add_exp Error: {e}")
215
 
@@ -217,12 +226,11 @@ async def add_exp(member_id):
217
  @bot.event
218
  async def on_message(message):
219
  try:
220
- if message.author.id not in bot_ids:
221
  if "!help_xp" not in message.content:
222
  print(f"adding exp from message {message.author}")
223
  await asyncio.sleep(1)
224
  await add_exp(message.author.id)
225
- #await periodic_api_test() # run this ~1 per day otherwise will lead to issues
226
  await bot.process_commands(message)
227
  except Exception as e:
228
  print(f"on_message Error: {e}")
@@ -240,7 +248,7 @@ async def on_reaction_add(reaction, user):
240
 
241
 
242
  @bot.command(name='update_leaderboard')
243
- async def update_leaderboard(ctx, num_results: int = 10):
244
  if ctx.author.id == 811235357663297546:
245
  await asyncio.sleep(1)
246
  worksheet = gspread_bot.open("levelbot").sheet1
@@ -251,7 +259,6 @@ async def update_leaderboard(ctx, num_results: int = 10):
251
  channel = bot.get_channel(1197143964994773023)
252
  message = await channel.fetch_message(1197148293164187678)
253
 
254
-
255
  # for 3 lists
256
  combined_list = [list(sublist) for sublist in zip(names_list, levels_list, exp_list)]
257
  combined_list = [[name, int(level), int(exp)] for name, level, exp in combined_list]
@@ -300,113 +307,9 @@ async def xp_help(ctx):
300
  help_message = "How to earn Discord / Hub exp: Post messages, react, Like, discuss, create repos and papers"
301
  await ctx.author.send(help_message)
302
 
303
-
304
- @bot.command()
305
- async def write_csv(ctx):
306
- if ctx.author.id == 811235357663297546:
307
- worksheet = gspread_bot.open("levelbot").sheet1
308
- values = worksheet.get_all_values()
309
- target_id = '811235357663297546'
310
- variable_xp = 0
311
-
312
- csv_file_path = 'test.csv'
313
- with open(csv_file_path, 'w', newline='') as csv_file:
314
- csv_writer = csv.writer(csv_file)
315
- csv_writer.writerows(values)
316
-
317
- # modifying csv data
318
- with open(csv_file_path, 'r') as csv_file:
319
- csv_reader = csv.reader(csv_file)
320
- rows = list(csv_reader)
321
-
322
- for row in rows:
323
- print(row)
324
- if target_id in row:
325
- index_of_target = row.index(target_id)
326
-
327
- # 2 to right
328
- cell_to_increment_index = index_of_target + 2
329
-
330
- # +10
331
- try:
332
- row[cell_to_increment_index] = str(int(row[cell_to_increment_index]) + variable_xp)
333
- print(row[cell_to_increment_index])
334
- except (IndexError, ValueError):
335
- print(f"Error: Unable to increment cell at index {cell_to_increment_index}")
336
-
337
- break
338
-
339
- # write modified data and send in discord
340
- with open(csv_file_path, 'w', newline='') as csv_file:
341
- csv_writer = csv.writer(csv_file)
342
- csv_writer.writerows(rows)
343
-
344
- csv_data_str = '\n'.join(','.join(row) for row in rows)
345
- csv_file = discord.File(csv_file_path)
346
-
347
- await ctx.channel.send(content="csv", file=csv_file)
348
-
349
- #target_user = await bot.fetch_user(int(target_id))
350
- #await target_user.send(content="csv", file=csv_file)
351
-
352
-
353
- @bot.command()
354
- async def read_csv(ctx):
355
- if ctx.author.id == 811235357663297546:
356
- async for message in ctx.channel.history(limit=10):
357
- if message.attachments:
358
- attachment = message.attachments[0]
359
- if attachment.filename.endswith('.csv'):
360
- csv_content = await attachment.read()
361
- csv_data = []
362
- csv_lines = csv_content.decode('utf-8').splitlines()
363
- csv_reader = csv.reader(csv_lines)
364
- for row in csv_reader:
365
- csv_data.append(row)
366
- print(csv_data)
367
-
368
- await ctx.send("discord -> read -> updated HF Hub")
369
- # react to the given message, helps with explainability
370
- await message.add_reaction('✅')
371
- break
372
-
373
-
374
-
375
- @bot.command()
376
- async def dataframe_test(ctx):
377
- if ctx.author.id == 811235357663297546:
378
-
379
-
380
- URL = "https://docs.google.com/spreadsheets/d/1hQSsIg1Y9WdBF_CdNM1L1rUUREoxKqRTe3_ILo-WK8w/edit#gid=0"
381
- csv_url = URL.replace('/edit#gid=', '/export?format=csv&gid=')
382
- df = pd.read_csv(csv_url)
383
- print(df)
384
-
385
- df['discord_user_id'] = df['discord_user_id'].astype(str)
386
-
387
-
388
-
389
- #worksheet = gspread_bot.open("levelbot").sheet1
390
- test_worksheet = gspread_bot.open("test").sheet1
391
-
392
- #df = get_as_dataframe(worksheet, dtype={'a': np.int64})
393
- set_with_dataframe(test_worksheet, df)
394
-
395
-
396
-
397
-
398
-
399
- def get_data():
400
-
401
- first_3_columns = data.iloc[:, 1:4] # Skip the first column and select the next three columns
402
- first_3_columns.to_csv('first_3_columns.csv', index=False)
403
- return first_3_columns
404
-
405
-
406
  # embeds with user pfps?
407
  # name, pfp, time in server....
408
 
409
-
410
  # discord_level column
411
  # pick 10 highest
412
  # update
@@ -415,24 +318,19 @@ def get_data():
415
  # count number of messages per user for every channel (total messages)
416
  # fix sheet if necessary
417
 
418
-
419
  # might need cell location data to pull both level and username at same time
420
  # add emojis for some color
421
  # check if members are still in the server
422
 
423
-
424
  """"""
425
  DISCORD_TOKEN = os.environ.get("DISCORD_TOKEN", None)
426
  def run_bot():
427
  bot.run(DISCORD_TOKEN)
428
  threading.Thread(target=run_bot).start()
429
 
430
- URL = "https://docs.google.com/spreadsheets/d/1hQSsIg1Y9WdBF_CdNM1L1rUUREoxKqRTe3_ILo-WK8w/edit#gid=0"
431
- csv_url = URL.replace('/edit#gid=', '/export?format=csv&gid=')
432
 
433
  def get_data():
434
- data = pd.read_csv(csv_url)
435
- first_3_columns = data.iloc[:, 1:4]
436
  first_3_columns.to_csv('first_3_columns.csv', index=False)
437
  return first_3_columns
438
 
@@ -443,11 +341,10 @@ def get_data():
443
 
444
  demo = gr.Blocks()
445
  with demo:
446
- dataframe1 = pd.read_csv(csv_url)
447
- column_values_unique = sorted(dataframe1.iloc[:, 3].unique())
448
  dataframe2 = pd.DataFrame({'Levels': column_values_unique})
449
  counts = {}
450
- for value in dataframe1.iloc[:, 3]:
451
  counts[value] = counts.get(value, 0) + 1
452
  dataframe2['Members'] = dataframe2['Levels'].map(counts)
453
 
@@ -479,4 +376,4 @@ with demo:
479
 
480
  #with gr.TabItem("📈 Hub-only leaderboard", elem_id="hub-table", id=2):
481
 
482
- demo.queue().launch()
 
15
  import logging
16
  import time
17
  import pandas as pd
18
+ from apscheduler.schedulers.background import BackgroundScheduler
19
  from gspread_dataframe import get_as_dataframe, set_with_dataframe
20
  from gspread_formatting.dataframe import format_with_dataframe
21
  import numpy as np
22
 
 
23
  import gradio_client
24
  import gradio as gr
25
  from gradio_client import Client
 
48
  """"""
49
  api = HfApi()
50
  """"""
51
+ #csv_file = 'data.csv'
52
+ global_df = pd.DataFrame()
53
 
54
  @bot.event
55
  async def on_ready():
56
+ global global_df
57
  print(f'Logged in as {bot.user.name}')
58
  print(f"XP_PER_MESSAGE: {XP_PER_MESSAGE}")
59
+ # testing sheet -> read -> paste sheet
60
+
61
+ """import data from google sheets -> HF Space .csv (doesn't make API call this way, as it's read-only)"""
62
+ data = pd.read_csv("https://docs.google.com/spreadsheets/d/1hQSsIg1Y9WdBF_CdNM1L1rUUREoxKqRTe3_ILo-WK8w/export?format=csv&gid=0")
63
+ data['discord_user_id'] = data['discord_user_id'].astype(str)
64
+ global_df = data
65
+ print(f"csv successfully retrieved: {global_df}")
66
+ #data.to_csv(csv_file, index=False)
67
+
68
+
69
+ def update_google_sheet():
70
+ """save data from HF Space -> google sheets (makes 1 API call)"""
71
+ print("test")
72
+ name = "levelbot"
73
+ worksheet = gspread_bot.open(name).sheet1
74
+ set_with_dataframe(worksheet, global_df)
75
+ print({f"Google sheet {name} successfully updated!"})
76
+
77
+ """
78
+ scheduler = BackgroundScheduler()
79
+ scheduler.add_job(update_google_sheet, "interval", seconds=60)
80
+ scheduler.start()
81
+
82
+ """
83
 
84
 
85
  def calculate_level(xp):
 
92
 
93
  processed_users = set()
94
 
95
+ async def periodic_api_test(): # needs rewrite, can do same thing and interact with csv -> push to google sheets
96
  try:
97
  await asyncio.sleep(1)
98
  column_values_3 = worksheet2.col_values(3)
 
124
  print(f"Failed to retrieve data for user {user}. Status code: {response.status_code}")
125
 
126
  except Exception as e:
127
+ print(f"periodic_api_test Error: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
 
129
 
130
  async def add_exp(member_id):
131
  try:
132
+ global global_df
 
 
133
 
134
  guild = bot.get_guild(879548962464493619)
135
  member = guild.get_member(member_id)
 
171
  21: lvl21, 22: lvl22, 23: lvl23, 24: lvl24, 25: lvl25, 26: lvl26, 27: lvl27, 28: lvl28, 29: lvl29, 30: lvl30,
172
  }
173
 
174
+ member_found = False
175
+ for index, cell_value in global_df.iloc[:, 0].items():
176
+ if cell_value == member_id:
177
+ # if found, update that row...
178
+ member_found = True
179
+ print(f"Record for {member} found at row {index + 1}, column 1")
180
+
181
+ # increment the old experience value (better not to replace outright)
182
+ old_xp = global_df.loc[index, 'discord_exp']
183
+ print(old_xp)
184
+ new_xp = old_xp + XP_PER_MESSAGE
185
+ print(f"new_xp = old_xp + XP_PER_MESSAGE / {new_xp} = {old_xp} + {XP_PER_MESSAGE}")
186
+ global_df.loc[index, 'discord_exp'] = new_xp # do not change column name
187
+ print(f"Record for {member} updated from {old_xp} to {new_xp} (+{XP_PER_MESSAGE}) ")
188
+ print(f"Current value: {global_df.loc[index, 'discord_exp']}")
189
+
190
+ # level up
191
+ current_level = calculate_level(new_xp)
192
+ print(f"Current_level for {member}: {current_level}")
193
+ if current_level >= 2 and current_level <=30:
194
+ current_role = lvls[current_level]
195
+ if current_role not in member.roles:
196
+ await member.add_roles(current_role)
197
+ print(f"Level Up! Gave {member} {current_role}")
198
+ await member.remove_roles(lvls[current_level-1])
199
+ print(f"Removed {lvls[current_level-1]} from {member}")
200
+ #print(f"{member} Level up! {current_level-1} -> {current_level}!")
201
+ #if current_role in member.roles: # needs update; reference exp reward for verification
202
+ #await member.send(f"Level up! {current_level-1} -> {current_level}!")
203
+
204
+ if not member_found:
205
+ # if not, create new record
206
+ print(f"creating new record for {member}")
207
+ #string_member_id = str(member.id)
208
+ xp = 10 # define somewhere else?
209
+ current_level = calculate_level(xp)
210
+ member_name = member.name
211
+ row_data = [member_id, member_name, xp, current_level]
212
+ new_row_df = pd.DataFrame([row_data], columns=global_df.columns)
213
+ updated_df = global_df.append(new_row_df, ignore_index=True)
214
+ # initial role assignment
215
+ if current_level == 1:
216
+ if lvl1 not in member.roles:
217
+ await member.add_roles(lvl1)
218
+ print(f"Gave {member} {lvl1}") # can log this better
219
+
220
+ if member_id == 811235357663297546:
221
+ update_google_sheet()
222
  except Exception as e:
223
  print(f"add_exp Error: {e}")
224
 
 
226
  @bot.event
227
  async def on_message(message):
228
  try:
229
+ if message.author.id not in bot_ids: # could change to if author does not have bot role (roleid)
230
  if "!help_xp" not in message.content:
231
  print(f"adding exp from message {message.author}")
232
  await asyncio.sleep(1)
233
  await add_exp(message.author.id)
 
234
  await bot.process_commands(message)
235
  except Exception as e:
236
  print(f"on_message Error: {e}")
 
248
 
249
 
250
  @bot.command(name='update_leaderboard')
251
+ async def update_leaderboard(ctx, num_results: int = 10): # needs rewrite
252
  if ctx.author.id == 811235357663297546:
253
  await asyncio.sleep(1)
254
  worksheet = gspread_bot.open("levelbot").sheet1
 
259
  channel = bot.get_channel(1197143964994773023)
260
  message = await channel.fetch_message(1197148293164187678)
261
 
 
262
  # for 3 lists
263
  combined_list = [list(sublist) for sublist in zip(names_list, levels_list, exp_list)]
264
  combined_list = [[name, int(level), int(exp)] for name, level, exp in combined_list]
 
307
  help_message = "How to earn Discord / Hub exp: Post messages, react, Like, discuss, create repos and papers"
308
  await ctx.author.send(help_message)
309
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
310
  # embeds with user pfps?
311
  # name, pfp, time in server....
312
 
 
313
  # discord_level column
314
  # pick 10 highest
315
  # update
 
318
  # count number of messages per user for every channel (total messages)
319
  # fix sheet if necessary
320
 
 
321
  # might need cell location data to pull both level and username at same time
322
  # add emojis for some color
323
  # check if members are still in the server
324
 
 
325
  """"""
326
  DISCORD_TOKEN = os.environ.get("DISCORD_TOKEN", None)
327
  def run_bot():
328
  bot.run(DISCORD_TOKEN)
329
  threading.Thread(target=run_bot).start()
330
 
 
 
331
 
332
  def get_data():
333
+ first_3_columns = global_df.iloc[:, 1:4]
 
334
  first_3_columns.to_csv('first_3_columns.csv', index=False)
335
  return first_3_columns
336
 
 
341
 
342
  demo = gr.Blocks()
343
  with demo:
344
+ column_values_unique = sorted(global_df.iloc[:, 3].unique())
 
345
  dataframe2 = pd.DataFrame({'Levels': column_values_unique})
346
  counts = {}
347
+ for value in global_df.iloc[:, 3]:
348
  counts[value] = counts.get(value, 0) + 1
349
  dataframe2['Members'] = dataframe2['Levels'].map(counts)
350
 
 
376
 
377
  #with gr.TabItem("📈 Hub-only leaderboard", elem_id="hub-table", id=2):
378
 
379
+ demo.queue().launch()