lunarflu HF staff commited on
Commit
63aba02
1 Parent(s): cddac94

add_exp rewrite, do interactions in csv in memory, push to google sheets on interval with scheduler (1 API call total)

Browse files
Files changed (1) hide show
  1. app.py +70 -160
app.py CHANGED
@@ -15,6 +15,7 @@ from tabulate import tabulate
15
  import logging
16
  import time
17
  import pandas as pd
 
18
 
19
  import gradio_client
20
  import gradio as gr
@@ -44,23 +45,34 @@ bot_ids = [1136614989411655780, 1166392942387265536, 1158038249835610123, 113077
44
  """"""
45
  api = HfApi()
46
  """"""
47
- #csv_file = 'import.csv'
48
-
49
 
50
  @bot.event
51
  async def on_ready():
 
52
  print(f'Logged in as {bot.user.name}')
53
  print(f"XP_PER_MESSAGE: {XP_PER_MESSAGE}")
54
  # testing sheet -> read -> paste sheet
55
 
56
- URL = "https://docs.google.com/spreadsheets/d/1hQSsIg1Y9WdBF_CdNM1L1rUUREoxKqRTe3_ILo-WK8w/edit#gid=0"
57
- csv_url = URL.replace('/edit#gid=', '/export?format=csv&gid=')
58
- data = pd.read_csv(csv_url)
59
- data.to_csv('data.csv', index=False)
60
- data = open('data.csv', 'r').read()
61
- print(data)
62
- gspread_bot.import_csv('1YJEwP7kZChI3Z2GKv4zFEfwwyQrO3zwXclv0QMrkOqA', data)
63
- #worksheet_test.batch_update(["A1:D30", "a"])
 
 
 
 
 
 
 
 
 
 
 
64
 
65
 
66
  def calculate_level(xp):
@@ -73,7 +85,7 @@ def calculate_xp(level):
73
 
74
  processed_users = set()
75
 
76
- async def periodic_api_test():
77
  try:
78
  await asyncio.sleep(1)
79
  column_values_3 = worksheet2.col_values(3)
@@ -105,59 +117,12 @@ async def periodic_api_test():
105
  print(f"Failed to retrieve data for user {user}. Status code: {response.status_code}")
106
 
107
  except Exception as e:
108
- print(f"periodic_api_test Error: {e}")
109
-
110
-
111
- def blocking_io(member_id):
112
- try:
113
- time.sleep(1)
114
- worksheet = gspread_bot.open("levelbot").sheet1
115
-
116
- guild = bot.get_guild(879548962464493619)
117
- member = guild.get_member(member_id)
118
- print(f" {member}")
119
- print(f"2")
120
-
121
- cell = worksheet.find(str(member.id))
122
- length = len(worksheet.col_values(1))
123
- print(f"3")
124
- if cell is None:
125
- print(f"creating new record for {member}")
126
- # if not, create new record
127
- string_member_id = str(member.id)
128
- xp = 10
129
- current_level = calculate_level(xp)
130
- member_name = member.name
131
- worksheet.update(values=[[string_member_id, member_name, xp, current_level]], range_name=f'A{length+1}:D{length+1}')
132
- # initial role assignment
133
- if current_level == 1:
134
- if lvl1 not in member.roles:
135
- return(1)
136
-
137
- else:
138
- print(f"4")
139
- if cell:
140
- # if so, update that row...
141
- xp = worksheet.cell(cell.row, cell.col+2).value
142
- xp = int(xp) + XP_PER_MESSAGE
143
- current_level = calculate_level(xp)
144
- print(f"updating record for {member}: {xp} xp")
145
- # write with added xp
146
- worksheet.update(values=[[xp, current_level]], range_name=f'C{cell.row}:D{cell.row}')
147
- # level up
148
- print(f"current_level: {current_level}")
149
- if current_level >= 2 and current_level <=30:
150
- # pass current_level as int?
151
- return(current_level)
152
- except Exception as e:
153
- print(f"blocking_io Error: {e}")
154
 
155
 
156
  async def add_exp(member_id):
157
  try:
158
- await asyncio.sleep(1)
159
- loop = asyncio.get_running_loop()
160
- result = await loop.run_in_executor(None, blocking_io, member_id)
161
 
162
  guild = bot.get_guild(879548962464493619)
163
  member = guild.get_member(member_id)
@@ -199,24 +164,49 @@ async def add_exp(member_id):
199
  21: lvl21, 22: lvl22, 23: lvl23, 24: lvl24, 25: lvl25, 26: lvl26, 27: lvl27, 28: lvl28, 29: lvl29, 30: lvl30,
200
  }
201
 
202
- if result == 1:
203
- await member.add_roles(lvl1)
204
- print(f"Gave {member} {lvl1}")
205
-
206
- print(f"result: {result}")
207
- if result >= 2:
208
- current_level = result
209
- current_role = lvls[current_level]
210
- if current_role not in member.roles:
211
- await member.add_roles(current_role)
212
- print(f"Giving {member} {current_role}")
213
- await member.remove_roles(lvls[current_level-1])
214
- print(f"Removed {lvls[current_level-1]} from {member}")
215
- #print(f"{member} Level up! {current_level-1} -> {current_level}!")
216
- if current_role in member.roles:
217
- await member.send(f"Level up! {current_level-1} -> {current_level}!")
218
-
219
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
220
  except Exception as e:
221
  print(f"add_exp Error: {e}")
222
 
@@ -224,7 +214,7 @@ async def add_exp(member_id):
224
  @bot.event
225
  async def on_message(message):
226
  try:
227
- if message.author.id not in bot_ids:
228
  if "!help_xp" not in message.content:
229
  print(f"adding exp from message {message.author}")
230
  await asyncio.sleep(1)
@@ -247,7 +237,7 @@ async def on_reaction_add(reaction, user):
247
 
248
 
249
  @bot.command(name='update_leaderboard')
250
- async def update_leaderboard(ctx, num_results: int = 10):
251
  if ctx.author.id == 811235357663297546:
252
  await asyncio.sleep(1)
253
  worksheet = gspread_bot.open("levelbot").sheet1
@@ -258,7 +248,6 @@ async def update_leaderboard(ctx, num_results: int = 10):
258
  channel = bot.get_channel(1197143964994773023)
259
  message = await channel.fetch_message(1197148293164187678)
260
 
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,81 +296,9 @@ async def xp_help(ctx):
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
-
311
- @bot.command()
312
- async def write_csv(ctx):
313
- if ctx.author.id == 811235357663297546:
314
- worksheet = gspread_bot.open("levelbot").sheet1
315
- values = worksheet.get_all_values()
316
- target_id = '811235357663297546'
317
- variable_xp = 0
318
-
319
- csv_file_path = 'test.csv'
320
- with open(csv_file_path, 'w', newline='') as csv_file:
321
- csv_writer = csv.writer(csv_file)
322
- csv_writer.writerows(values)
323
-
324
- # modifying csv data
325
- with open(csv_file_path, 'r') as csv_file:
326
- csv_reader = csv.reader(csv_file)
327
- rows = list(csv_reader)
328
-
329
- for row in rows:
330
- print(row)
331
- if target_id in row:
332
- index_of_target = row.index(target_id)
333
-
334
- # 2 to right
335
- cell_to_increment_index = index_of_target + 2
336
-
337
- # +10
338
- try:
339
- row[cell_to_increment_index] = str(int(row[cell_to_increment_index]) + variable_xp)
340
- print(row[cell_to_increment_index])
341
- except (IndexError, ValueError):
342
- print(f"Error: Unable to increment cell at index {cell_to_increment_index}")
343
-
344
- break
345
-
346
- # write modified data and send in discord
347
- with open(csv_file_path, 'w', newline='') as csv_file:
348
- csv_writer = csv.writer(csv_file)
349
- csv_writer.writerows(rows)
350
-
351
- csv_data_str = '\n'.join(','.join(row) for row in rows)
352
- csv_file = discord.File(csv_file_path)
353
-
354
- await ctx.channel.send(content="csv", file=csv_file)
355
-
356
- #target_user = await bot.fetch_user(int(target_id))
357
- #await target_user.send(content="csv", file=csv_file)
358
-
359
-
360
- @bot.command()
361
- async def read_csv(ctx):
362
- if ctx.author.id == 811235357663297546:
363
- async for message in ctx.channel.history(limit=10):
364
- if message.attachments:
365
- attachment = message.attachments[0]
366
- if attachment.filename.endswith('.csv'):
367
- csv_content = await attachment.read()
368
- csv_data = []
369
- csv_lines = csv_content.decode('utf-8').splitlines()
370
- csv_reader = csv.reader(csv_lines)
371
- for row in csv_reader:
372
- csv_data.append(row)
373
- print(csv_data)
374
-
375
- await ctx.send("discord -> read -> updated HF Hub")
376
- # react to the given message, helps with explainability
377
- await message.add_reaction('✅')
378
- break
379
-
380
-
381
  # embeds with user pfps?
382
  # name, pfp, time in server....
383
 
384
-
385
  # discord_level column
386
  # pick 10 highest
387
  # update
@@ -390,12 +307,10 @@ async def read_csv(ctx):
390
  # count number of messages per user for every channel (total messages)
391
  # fix sheet if necessary
392
 
393
-
394
  # might need cell location data to pull both level and username at same time
395
  # add emojis for some color
396
  # check if members are still in the server
397
 
398
-
399
  """"""
400
  DISCORD_TOKEN = os.environ.get("DISCORD_TOKEN", None)
401
  def run_bot():
@@ -431,11 +346,6 @@ with demo:
431
  print("\nDataframe 2:")
432
  print(dataframe2)
433
 
434
-
435
-
436
-
437
-
438
-
439
  TITLE = """<h1 align="center" id="space-title">🤗 Hugging Face Level Leaderboard</h1>"""
440
  gr.HTML(TITLE)
441
  with gr.Tabs(elem_classes="tab-buttons") as tabs:
 
15
  import logging
16
  import time
17
  import pandas as pd
18
+ from apscheduler.schedulers.background import BackgroundScheduler
19
 
20
  import gradio_client
21
  import gradio as gr
 
45
  """"""
46
  api = HfApi()
47
  """"""
48
+ csv_file = 'data.csv'
 
49
 
50
  @bot.event
51
  async def on_ready():
52
+ global csv_file
53
  print(f'Logged in as {bot.user.name}')
54
  print(f"XP_PER_MESSAGE: {XP_PER_MESSAGE}")
55
  # testing sheet -> read -> paste sheet
56
 
57
+ """import data from google sheets -> HF Space .csv (doesn't make API call this way, as it's read-only)"""
58
+ data = pd.read_csv("https://docs.google.com/spreadsheets/d/1hQSsIg1Y9WdBF_CdNM1L1rUUREoxKqRTe3_ILo-WK8w/export?format=csv&gid=0")
59
+ print(f"csv successfully retrieved: {data}")
60
+ data.to_csv(csv_file, index=False)
61
+
62
+
63
+ def update_google_sheet():
64
+ """save data from HF Space -> google sheets (makes 1 API call)"""
65
+ data = open(csv_file, 'r').read()
66
+ # 1hQSsIg1Y9WdBF_CdNM1L1rUUREoxKqRTe3_ILo-WK8w = live
67
+ # 1YJEwP7kZChI3Z2GKv4zFEfwwyQrO3zwXclv0QMrkOqA = test
68
+ spreadsheet_id = "1hQSsIg1Y9WdBF_CdNM1L1rUUREoxKqRTe3_ILo-WK8w"
69
+ gspread_bot.import_csv('', data)
70
+ print{f"Google sheet {spreadsheet_id} successfully updated!"}
71
+
72
+
73
+ scheduler = BackgroundScheduler()
74
+ scheduler.add_job(func=update_google_sheet, trigger="interval", seconds=60)
75
+ scheduler.start()
76
 
77
 
78
  def calculate_level(xp):
 
85
 
86
  processed_users = set()
87
 
88
+ async def periodic_api_test(): # needs rewrite, can do same thing and interact with csv -> push to google sheets
89
  try:
90
  await asyncio.sleep(1)
91
  column_values_3 = worksheet2.col_values(3)
 
117
  print(f"Failed to retrieve data for user {user}. Status code: {response.status_code}")
118
 
119
  except Exception as e:
120
+ print(f"periodic_api_test Error: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121
 
122
 
123
  async def add_exp(member_id):
124
  try:
125
+ global csv_file
 
 
126
 
127
  guild = bot.get_guild(879548962464493619)
128
  member = guild.get_member(member_id)
 
164
  21: lvl21, 22: lvl22, 23: lvl23, 24: lvl24, 25: lvl25, 26: lvl26, 27: lvl27, 28: lvl28, 29: lvl29, 30: lvl30,
165
  }
166
 
167
+ data = pd.read_csv(csv_file)
168
+ for index, cell_value in data.iloc[:, 0].items():
169
+ if cell_value == member_id:
170
+ # if found, update that row...
171
+ print(f"Record for {member} found at row {index + 1}, column 1")
172
+
173
+ # increment the old experience value (better not to replace outright)
174
+ old_xp = data.loc[index, 'discord_exp']
175
+ new_xp = int(old_xp) + int(XP_PER_MESSAGE)
176
+ data.loc[index, 'discord_exp'] = new_xp # do not change column name
177
+ print(f"Record for {member} updated with {int(XP_PER_MESSAGE)} xp for a total of {new_xp} experience")
178
+
179
+ # level up
180
+ current_level = calculate_level(new_xp)
181
+ print(f"Current_level for {member}: {current_level}")
182
+ if current_level >= 2 and current_level <=30:
183
+ current_role = lvls[current_level]
184
+ if current_role not in member.roles:
185
+ await member.add_roles(current_role)
186
+ print(f"Level Up! Gave {member} {current_role}")
187
+ await member.remove_roles(lvls[current_level-1])
188
+ print(f"Removed {lvls[current_level-1]} from {member}")
189
+ #print(f"{member} Level up! {current_level-1} -> {current_level}!")
190
+ if current_role in member.roles:
191
+ await member.send(f"Level up! {current_level-1} -> {current_level}!")
192
+
193
+ else:
194
+ # if not, create new record
195
+ print(f"creating new record for {member}")
196
+ #string_member_id = str(member.id)
197
+ xp = 10 # define somewhere else?
198
+ current_level = calculate_level(xp)
199
+ member_name = member.name
200
+ row_data = [member_id, member_name, xp, current_level]
201
+ new_row_df = pd.DataFrame([row_data], columns=data.columns)
202
+ updated_df = data.append(new_row_df, ignore_index=True)
203
+ updated_df.to_csv(csv_file, index=False)
204
+ # initial role assignment
205
+ if current_level == 1:
206
+ if lvl1 not in member.roles:
207
+ await member.add_roles(lvl1)
208
+ print(f"Gave {member} {lvl1}") # can log this better
209
+
210
  except Exception as e:
211
  print(f"add_exp Error: {e}")
212
 
 
214
  @bot.event
215
  async def on_message(message):
216
  try:
217
+ if message.author.id not in bot_ids: # could change to if author does not have bot role (roleid)
218
  if "!help_xp" not in message.content:
219
  print(f"adding exp from message {message.author}")
220
  await asyncio.sleep(1)
 
237
 
238
 
239
  @bot.command(name='update_leaderboard')
240
+ async def update_leaderboard(ctx, num_results: int = 10): # needs rewrite
241
  if ctx.author.id == 811235357663297546:
242
  await asyncio.sleep(1)
243
  worksheet = gspread_bot.open("levelbot").sheet1
 
248
  channel = bot.get_channel(1197143964994773023)
249
  message = await channel.fetch_message(1197148293164187678)
250
 
 
251
  # for 3 lists
252
  combined_list = [list(sublist) for sublist in zip(names_list, levels_list, exp_list)]
253
  combined_list = [[name, int(level), int(exp)] for name, level, exp in combined_list]
 
296
  help_message = "How to earn Discord / Hub exp: Post messages, react, Like, discuss, create repos and papers"
297
  await ctx.author.send(help_message)
298
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
299
  # embeds with user pfps?
300
  # name, pfp, time in server....
301
 
 
302
  # discord_level column
303
  # pick 10 highest
304
  # update
 
307
  # count number of messages per user for every channel (total messages)
308
  # fix sheet if necessary
309
 
 
310
  # might need cell location data to pull both level and username at same time
311
  # add emojis for some color
312
  # check if members are still in the server
313
 
 
314
  """"""
315
  DISCORD_TOKEN = os.environ.get("DISCORD_TOKEN", None)
316
  def run_bot():
 
346
  print("\nDataframe 2:")
347
  print(dataframe2)
348
 
 
 
 
 
 
349
  TITLE = """<h1 align="center" id="space-title">🤗 Hugging Face Level Leaderboard</h1>"""
350
  gr.HTML(TITLE)
351
  with gr.Tabs(elem_classes="tab-buttons") as tabs: