async def wordle_guess_cmd(self, ctx, word): """ Callback for the /wordle guess command -- input: ctx: interactions.CommandContext word: str """ await ctx.defer(ephemeral=True) await utils.custom_assert("current_event" in db.keys(), "No current event registered", ctx) current_event = eval(db["current_event"]) await utils.custom_assert( isinstance(current_event, events.Wordle_event), "The current event is not a wordle", ctx) wordle = Wordle(db["word_of_the_day"]) user_id = str(int(ctx.author.id)) if user_id not in db["wordle_guesses"].keys(): db["wordle_guesses"][user_id] = [] guesses = list(db["wordle_guesses"][user_id]) word = word.lower() await utils.custom_assert( len(guesses) < wordle.nb_trials, "The maximum amount of trials has been reached!", ctx) await utils.custom_assert(wordle.is_valid(word), "This is not a valid word!", ctx) await utils.custom_assert( guesses == [] or wordle.solution != guesses[-1], "You already won!", ctx) guesses.append(word) db["wordle_guesses"][user_id] = guesses header_str = "\n".join(wordle.guess(w) for w in guesses) if guesses[-1] == wordle.solution: header_str += f"\n\nCongratulations, you found the word of the day with {len(guesses)}/{wordle.nb_trials} trials!\nYou earnt {current_event.reward}{Constants.PIFLOUZ_EMOJI}" piflouz_handlers.update_piflouz(user_id, current_event.reward, check_cooldown=False) elif len(guesses) == wordle.nb_trials: header_str += f"\n\nOuch, you failed :(\nThe answer was: **{wordle.solution}**" await self.send_wordle_embed(ctx, wordle, guesses, header_str)
async def allstat_msg(message): #next update with embeds enabled if (message.content.lower() == 'bb allstats' or message.content.lower() == 'bb allprofile'): if (str(message.author.id) in db.keys()): data = get_profile(db[str(message.author.id)]) if ('error' in data): return await message.channel.send(data['error']['message']) clan = "" if ("clan" in data): clan = "\nClan: " + data['clan']['clan_name'] await message.channel.send( f"Name: {data['name'].encode('latin').decode()}\nLevel: {data['level']}\nGames: {data['games']}\tWins: {data['wins']}\nBest legend: " + max(data['legends'], key=lambda x: x['level']) ['legend_name_key'].capitalize() + clan) return await message.channel.send(get_setup())
async def showWeeklyRanking(ctx): posters = [] keys = db.keys() for key in keys: user = getUser(key) posters.append({"User": user.userName, "Week":user.week}) posters.sort(key=getWeek, reverse=True) message = "This weeks rankings so far:" index = 1; for poster in posters: message += "\n{}. {} with {}".format(index, poster.get("User"), poster.get("Week")) index += 1 await ctx.send(message)
async def delete_word(self, message, word): if DATABASE_WORDS not in db.keys(): return channel = message.channel # Get the database and attempt to remove the word. A ValueError is thrown # if the word is not in the database. words = db[DATABASE_WORDS] try: words.remove(word) await self.send_message( channel, "Successfully removed {0} from database".format(word)) except ValueError: await self.send_message(channel, "{0} is not in the database".format(word))
def update_encouragements(encouraging_message): #check if encouragements is a key in the database if "encouragements" in db.keys(): #then get all the values encouragements key in the database encouragements = db["encouragements"] #adding encouraging messages encouragements.append(encouraging_message) #updateing in the database db["encouragements"] = encouragements #if there aren't any encouragements in database else: db["encouragements"] = [encouraging_message]
def list_encouragements(): if "encouragements" in db.keys(): encouragements = list(db["encouragements"]) else: encouragements = list() encouragements_message = "" counter = 1 if encouragements: for encouragement in encouragements: encouragements_message += f"{str(counter)}. {encouragement}\n" counter += 1 else: encouragements_message = f"No custom encouragements yet. Type ``{prefix}new`` to add some." return encouragements_message
def aggiungi_nandata(ctx, comando_in, parola): global flagDuplicato if ctx.invoked_with == 'nando': nome_db = comando_in[:-1] + comando_in[-1].replace('o', 'i') else: nome_db = comando_in parola_interna = parola if nome_db in db.keys(): database = db[nome_db] if parola_interna in database: flagDuplicato = not flagDuplicato else: database.append(parola_interna) else: database = [parola_interna] db[nome_db] = database
async def on_message(message): if message.author == client.user: return msg = message.content if msg.startswith("$addguild"): x = msg.split(" ", 3)[1:] m_guild = x[0] m_server = x[1] if string_length(m_server) == 4: db[m_guild] = m_server await message.channel.send("New guild added successfully.") else: await message.channel.send("Incorrect channel. Channel must be format of <Ser3> or <Med1>, etc.") if msg.startswith("$listguilds"): for key in db.keys(): await message.channel.send(key + ' ' + db[key]) if msg.startswith("$help"): await message.channel.send("$help - lists commands") await message.channel.send("$addguild <guildname> <mainchannel> - adds a guild and their main channel. Will overwrite previous data") await message.channel.send("$delguild <guildname> - deletes guild specified") await message.channel.send("$guild <guildname> - lists main server for guild specified") await message.channel.send("$listguilds - lists all guilds and main servers") if msg.startswith("$guild"): x = msg.split(" ", 3)[1:] m_guild = x[0] x = m_guild.lower() for key in db: y = key.lower() if x == y: await message.channel.send(db[key]) break if msg.startswith("$delguild"): x = msg.split(" ", 3)[1:] m_guild = x[0] x = m_guild.lower() for key in db: y = key.lower() if x == y: del db[key] await message.channel.send("Guild deleted successfully.") break
def le_lb(): # var = db[str(ctx.author.id)] keys = db.keys() list_of_dicts = [] for user_key in keys: if user_key != "tags" and user_key != "server": value_check(user_key, "lvl", 0) value_check(user_key, "lvl_xp", 0) # user_key is just a key (aka string) u = db[str(user_key)] # get the db value of the key lvl = u["lvl"] lvl_xp = u["lvl_xp"] # lvl_next = u["lvl_next"] # we don't need this lol user_dict = { "id": user_key, "level": lvl, "xp": lvl_xp } # this way, our data can be used easily list_of_dicts.append(user_dict) # print(list_of_dicts) def myFunc(e): return e["level"] list_of_dicts.sort(reverse=True, key=myFunc) new_list = [] iterator = 0 for u in list_of_dicts: iterator += 1 # this is a list of strings instead of # a list of dictionaries string = f"`{iterator}` | <@{u['id']}> - level {u['level']}" new_list.append(string) description = "\n".join(new_list) embed = discord.Embed(title=f"Levelling Leaderboard", description=description) return embed
async def classes(ctx): has_class = False # to check if the user has joined any classes for role in ctx.author.roles: if role.name in db.keys(): try: embed = discord.Embed( title=f'{db[role.name][0]} {db[role.name][1]}', description=db[role.name][2].replace('|', ','), color=0x57afdb) embed.add_field(name='Units', value=db[role.name][3], inline=True) embed.add_field(name='Schedule', value=db[role.name][4], inline=True) embed.add_field(name='Professor', value=db[role.name][6].replace('|', ','), inline=True) embed.add_field(name='Zoom Link', value=db[role.name][14], inline=True) await ctx.send(embed=embed) await ctx.send( f'Zoom link for the class {role.name} added by: <@{db[role.name][15]}>' ) except: embed = discord.Embed( title=f'{db[role.name][0]} {db[role.name][1]}', description=db[role.name][2].replace('|', ','), color=0x57afdb) embed.add_field(name='Units', value=db[role.name][3], inline=True) embed.add_field(name='Schedule', value=db[role.name][4], inline=True) embed.add_field(name='Professor', value=db[role.name][6].replace('|', ','), inline=True) embed.add_field( name='Zoom Link', value='The zoom link is not found in our database.', inline=True) await ctx.send(embed=embed) has_class = True if not has_class: ctx.send('You have not joined any classes.')
async def add(self, ctx, key, *args): """| add key or multiple new values""" if key in db.keys(): values = db[key] for value in args: values.append(value) db[key] = values else: if args: values = [] for value in args: values.append(value) db[key] = values else: db[key] = [] await ctx.send(f'perfecto, añadido!')
def getTrivia(amount, category, difficulty): conn = http.client.HTTPSConnection("opentdb.com") if "quizkey" not in db.keys(): key = getSession(conn, 3) key = db["quizkey"] while True: conn.request( 'GET', '/api.php?amount=' + amount.content + '&category=' + category + '&difficulty=' + difficulty.content + '&type=multiple&token=' + key) response = conn.getresponse() json_data = json.loads(response.read()) if json_data['response_code'] == 0: return json_data else: print("Getting a new session key...\n") key = getSession(conn, json_data['response_code'])
def AddItemToDatabase(itemName): itemName = itemName[:-1] if 'MarketItemList' in db.keys(): if(itemName in db['MarketItemList']): print('Item already added.') return False itemList = db['MarketItemList'] itemList.append(itemName) db['MarketItemList'] = itemList else: db['MarketItemList'] = [itemName] print(db['MarketItemList']) return True
def list_encouragements(): """ Returns a list of all currently saved encouraging messages """ encouragements = [] response = 'I currently have the following **extra** messages: \n' if 'encouragements' in db.keys(): encouragements = db['encouragements'].value for i, enc in enumerate(encouragements): response += f'{i+1}. *{enc}*\n' response += '\nI also have these **starter** messages:\n' for i, enc in enumerate(starter_encouragements): response += f'{i+1}. *{enc}*\n' return response
async def clear(ctx): i = 0 for role in ctx.author.roles: if role.name in db.keys(): await ctx.author.remove_roles(role) if i == 0: classes_removed = role.name i += 1 continue classes_removed += ', ' + role.name embed = discord.Embed( title='<a:check:859805173051293696> Successfully cleared your classes!', description=f"You were removed from these classes: {classes_removed}", color=0x57afdb) await ctx.send(embed=embed) await cleardb(ctx)
def addCurr(person, amount): if person in db.keys(): value = int(db[person]['currency']) value += amount db[person] = { 'currency': '%d' % (value), 'last_daily': '%s' % (db[person]['last_daily']) } return db[person]['currency'] else: setUp(person) value = int(db[person]['currency']) value += amount db[person] = { 'currency': '%d' % (value), 'last_daily': '%s' % (db[person]['last_daily']) } return db[person]['currency']
async def update_rank_mega_piflexer(bot): """ Removes the mega-piflexer roles when they need to be -- input: bot: interactions.Client """ if "mega_piflexers" not in db.keys(): return t = time.time() guild = Guild(id=Constants.GUILD_IDS[0], _client=bot._http) role = Role(id=Constants.MEGA_PIFLEXER_ROLE_ID) for id, old_time in db["mega_piflexers"].items(): if t - old_time >= Constants.MEGA_PIFLEXER_ROLE_DURATION: member = await guild.get_member(int(id)) await member.remove_role(role, guild_id=guild.id) del db["mega_piflexers"][id]
async def earn(self, ctx, amt): ''' CREATE / UPDATE ''' me = ctx.author # sets me to your Member userdata = {} if me.id not in db.keys( ): #CREATE: checks to see if there is a key with your ID first userdata["coins"] = 0 db[me.id] = json.dumps(userdata) userdata = json.loads( db[me.id]) #UPDATE: loads the prev coins and adds the new ones newcoins = int(amt) + userdata["coins"] userdata.update({"coins": newcoins}) db[me.id] = json.dumps(userdata) await ctx.send( f"{me.name} just saved {amt} coins for a total of {newcoins}")
def update_piflouz(user_id, qty=None, check_cooldown=True, current_time=None): """ This function does the generic piflouz mining, and returns wether it suceeded or not -- input: user_id: int/str -> id of the person who reacted qty: int -> number of piflouz (not necesseraly positive) check_cooldown: boolean -> if we need to check the cooldown (for the piflouz mining) -- output: res: boolean -> if the update succeded qty: int -> the amount actually sent/received (only returned if check_cooldown = True (corresponding to a /get)) current_time: int -> the time at which the interaction was created """ if "piflouz_bank" not in db.keys(): db["piflouz_bank"] = dict() user_id = str(user_id) # New user if user_id not in db["piflouz_bank"].keys(): db["piflouz_bank"][user_id] = 0 db["timers_react"][user_id] = 0 balance = db["piflouz_bank"][user_id] if check_cooldown: # corresponding to a /get assert current_time is not None, "Got current_time = None" cooldown = utils.get_timer(user_id, current_time) qty = get_total_piflouz_earned(user_id, current_time) else: assert qty is not None, "Got qty = None" if (not check_cooldown or cooldown == 0) and balance + qty >= 0: db["piflouz_bank"][user_id] = balance + qty if check_cooldown: db["timers_react"][user_id] = current_time return True, qty return True if check_cooldown: return False, qty return False
async def get_embed_raffle(self, bot): """ Returns an embed message corresponding to the raffle message -- input: bot: interactions.Client """ desc = f"Here is the new raffle! Use `/raffle n` to buy `n` 🎟️!\n\ They cost {self.ticket_price} {Constants.PIFLOUZ_EMOJI} each\n\ The user with the winning ticket will earn {100 - self.tax_ratio}% of the total money spent by everyone!" fields = [] if "raffle_participation" in db.keys() and len( db["raffle_participation"]) > 0: participation = db["raffle_participation"] async def get_str(key_val): user_id, nb_tickets = key_val return f"<@{user_id}> - {nb_tickets}\n" tasks = [get_str(key_val) for key_val in participation.items()] res = await asyncio.gather(*tasks) val = "".join(res) total_prize = self.get_raffle_total_prize() fields.append( EmbedField(name="Current 🎟️ bought", value=val, inline=False)) fields.append( EmbedField( name="Total prize", value= f"The winner will earn {total_prize} {Constants.PIFLOUZ_EMOJI}!", inline=False)) embed = Embed( title="New Raffle!", description=desc, color=Color.random().value, thumbnail=EmbedImageStruct(url=Constants.PIBOU4STONKS_URL)._json, fields=fields) return embed
def get_rank(userid): """ Returns the userid's rank from the leaderboard. """ # var = db[str(ctx.author.id)] keys = db.keys() list_of_dicts = [] value_check(userid, "lvl", 0) value_check(userid, "lvl_xp", 0) for user_key in keys: if user_key != "tags" and user_key != "server": # user_key is just a key (aka string) u = db[str(user_key)] # get the db value of the key print(u) value_check(user_key, "lvl", 0) value_check(user_key, "lvl_xp", 0) lvl = u["lvl"] lvl_xp = u["lvl_xp"] # lvl_next = u["lvl_next"] # we don't need this lol user_dict = { "id": user_key, "level": lvl, "xp": lvl_xp } # this way, our data can be used easily list_of_dicts.append(user_dict) def myFunc(e): return e["level"] # orders the list list_of_dicts.sort(reverse=True, key=myFunc) iterator = 0 for u in list_of_dicts: iterator += 1 # iterates through ordered list # to look for matching user if str(u["id"]) == str(userid): return iterator """
def find_tag(tag: str): """ Looks for a tag in the database and returns `key`, `value`, and `status`. \n Also initiates the tag database if not available. \n 200 success | 404 not found | 500 error """ print(f"finding tag {tag} . . .") keys = db.keys() # lists the database keys if "tags" not in keys: # to make sure there's a database db["tags"] = {} # creates the tag database print(f"Initiated databse . . .") tags = db["tags"] # sets the database to a variable for easy use # tags is a dictionary with keys and values # to access a tag, use tags[tag] return_value = None if tag in tags: return_value = { "key": tag, # gets the tag name "value": tags[tag], # gets the tag value frome db "status": 200 } print(f"Tag {tag} found with value {tags[tag]}.") elif tag not in tags: return_value = { "key": tag, # gets the supposed tag name "value": f"Tag `{tag}` doesn't exist.", # returns none "status": 404 } print(f"Tag {tag} not found.") if tag == None: return_value["value"] = None else: return_value = {"key": None, "value": None, "status": 500} print(f"An error occured finding {tag}.") return return_value
async def on_message(message): if message.author == client.user: return msg = message.content if msg.startswith('$inspire'): quote = get_quote() await message.channel.send(quote) if db["responding"]: options = starter_encouragements if "encouragements" in db.keys(): options = options + db["encouragements"] if any(word in msg for word in sad_words): await message.channel.send(random.choice(options)) if msg.startswith("$responding"): value = msg.split("$responding ",1)[1] if value.lower() == "true": db["responding"] = True await message.channel.send("Responding is on.") else: db["responding"] = False await message.channel.send("Responding is off.") if message.author == client.user: return elif message.content.startswith('$hello'): await message.channel.send('Hello!') elif message.content.startswith('$ping'): await message.channel.send('Pong!') elif message.content.startswith('$howru'): await message.channel.send('I am Good !') elif message.content.startswith('$whoru'): await message.channel.send('I am a BOT. I am a program !') elif message.content.startswith('$help'): await message.channel.send('1.$ping \n 2.$howru \n 3.$whoru \n for help type $help')
def on_spawn_day(): today = datetime.datetime.now(IST) today = today.strftime("%m-%d %H:%M:%S") # today = "12-30 00:00:00" today = datetime.datetime.strptime(today,"%m-%d %H:%M:%S") # print(today) keys = db.keys() flag = 0 for k in keys: spawn_day = db[k] spawn_day = datetime.datetime.strptime(spawn_day,"%Y-%m-%d %H:%M:%S") spawn_day = spawn_day.strftime("%m-%d %H:%M:%S") spawn_day = datetime.datetime.strptime(spawn_day,"%m-%d %H:%M:%S") # print(spawn_day) if today ==spawn_day: print(k) return k if flag == 0: return -1
async def start_new_season(bot): """ Announces the beginning of a new season -- input: bot: interactions.Client -- output: msg: interactions.Message -> the message sent """ if "out_channel" in db.keys(): channel = await bot.get_channel(db["out_channel"]) emoji = Emoji(id=Constants.PIFLOUZ_EMOJI_ID) piflouz_button = Button(style=ButtonStyle.SECONDARY, label="", custom_id=Cog_piflouz_mining.button_name, emoji=emoji._json) msg = await channel.send(embeds=embed_messages.get_embed_piflouz(bot), components=piflouz_button) return msg
async def dblist(self, ctx, member: discord.Member = False): ''' READ ALL: Lists all keys in DB created. ''' if not member: dbkeys = db.keys() returnstr = "" for key in dbkeys: amember = ctx.guild.get_member(int(key)) returnstr += f"{amember.name}\n" try: await ctx.send(returnstr) except: await ctx.send("Empty Ass DB") finally: pass else: amember = db[int(member.id)] await ctx.send(amember)
def feed(): gen = FeedGenerator() gen.id(os.environ['SELF']) gen.title(os.environ['TITLE']) gen.link(href=os.environ['SELF'], rel='self') gen.link(href=os.environ['LINK'], rel='alternate') for k in sorted(db.keys()): fields = json.loads(db[k]) if 'URL' not in fields or fields.get('Save for later'): continue entry = gen.add_entry() entry.link(href=fields['URL']) entry.id(fields['URL']) entry.title(fields.get('Title', fields['URL'])) entry.updated(k.split('_')[0]) commentary = fields.get('Commentary') desc = fields.get('Description') summary = '' if commentary: summary += commentary if commentary and desc: summary += "\n\n" if desc: summary += "> " + desc if summary: entry.summary(summary) tags = [ re.sub(r'[^a-z]+', '-', tag.lower()) for tag in fields.get('Tags', '').split(',') ] rating = fields.get('Rating') if rating: tags.append(str(rating) + '-stars') for t in tags: if t: entry.category(term=t) body = gen.atom_str(pretty=True) return Response(body, mimetype='application/atom+xml')
async def delete_user(self, message): # If there is no database, don't do anything if DATABASE_USERS not in db.keys(): return channel = message.channel # Get the database and user name users = db[DATABASE_USERS] user = message.content.split()[1] try: users.pop(user, None) await self.send_message( channel, 'Successfully removed {0} from the database'.format(user)) except KeyError: await self.send_message( channel, 'User {0} does not exist in the database'.format(user))
async def on_end(self, bot): if "out_channel" not in db.keys(): return out_channel = await bot.get_channel(db["out_channel"]) # Disable previous deliveries delivery = db["last_birthday_delivery"] db["last_birthday_delivery"] = dict() if delivery != dict(): msg = await out_channel.get_message(delivery["id"]) components = components = [ self.get_component(emoji, nb, disabled=True) for emoji, nb in zip(self.ingredients, delivery["qty"].values()) ] await msg.edit("Unfortunately, the delivery person has left", components=components) embed = self.get_end_embed() await out_channel.send(embeds=embed)
async def leaderboard(client: discord.Client, message: discord.Message): keys = db.keys() names = [] value = [] for key in keys: try: print(int(key)) user = await client.fetch_user(int(key)) if user != None: print(user.name) names.append(user) except: print("err: "+key) names.sort(key=lambda x: db[str(x.id)]['ELO'][-1], reverse=True) description = "" for name in names: description += "{}: {}\n".format(name.name, db[str(name.id)]['ELO'][-1]) embed = discord.Embed(title="Leaderboard", description = description, color=0xf5a816) await message.channel.send(embed=embed)