Ejemplo n.º 1
0
async def continue_giveaway(data: dict):
    time_left: int = data['end'] - int(time.time())

    time_left_string: str = seconds_to_string(time_left)
    time_left_string_before: str = ''

    channel = client.get_channel(data['channel_id'])
    try:
        message = await channel.fetch_message(data['id'])
    except discord.errors.NotFound:
        await db.end_giveaway(data['id'])
        return

    while time_left > 0:
        # If it's gonna end in more than a minute, update every 30 seconds
        if time_left > 60:
            await asyncio.sleep(30)
        # If it's gonna end in more than 3 seconds, update every 2 seconds
        elif time_left > 3:
            await asyncio.sleep(2)
        # If it's gonna end in less than 3 seconds, update every second
        else:
            await asyncio.sleep(1)

        time_left = data['end'] - int(time.time())
        time_left_string = seconds_to_string(time_left)
        if time_left_string != time_left_string_before:
            await update_giveaway_message(message, data)
            time_left_string_before = time_left_string

    await update_giveaway_message(message, data)
    await end_giveaway(data)
Ejemplo n.º 2
0
def create_giveaway_embed(data: dict, winners=None):
    prize = data['prize']
    creator_id = data['creator_id']
    end = data['end']
    winner_count = data['winners']
    bobux_requirement = data['bobux_requirement']

    ended = time.time() > end

    if ended:
        if winners is None:
            description = f'**Winner: ...**'
        elif isinstance(winners, str):
            description = f'**Winner: {winners}**'
        elif len(winners) > 1:
            winners_mentions = ', '.join(winner.mention for winner in winners)
            description = f'**Winners: {winners_mentions}**'
        else:
            description = f'**Winner: {winners[0].mention}**'
    else:
        ends_in_string = seconds_to_string(end - int(time.time()))
        description = f'**Ends in: {ends_in_string}**'
        if winner_count != 1:
            description += f'\nWinners: {winner_count}'
        if bobux_requirement > 0:
            description += f'\nRequirement: {bobux_requirement} bobux'

    description += f'\nHosted by: <@{creator_id}>'

    embed = discord.Embed(title=prize,
                          description=description,
                          timestamp=datetime.fromtimestamp(end))

    return embed
Ejemplo n.º 3
0
async def run(message,
              member: Member,
              mute_length: Time = 0,
              reason: str = None):
    'Mutes a member for a specified amount of time'

    if not can_mute(message.author): return

    if not member or not mute_length:
        return await message.channel.send(
            'Invalid command usage. Example: **!mute gogourt 10 years nerd**')

    if reason:
        reason = reason.strip()

    mute_length_string = seconds_to_string(mute_length)

    if reason:
        mute_message = f'<@{member.id}> has been muted for {mute_length_string} for "**{reason}**".'
    else:
        mute_message = f'<@{member.id}> has been muted for {mute_length_string}.'

    await message.send(embed=discord.Embed(description=mute_message))

    await do_mute(message, member, mute_length, reason)
Ejemplo n.º 4
0
async def run(message, member: Member = None):
	'Tells you how long you (or another member) is muted for.'

	if not member:
		member = message.author

	mute_remaining = int((await db.get_mute_end(member.id)) - time.time())

	if mute_remaining < 0:
		await unmute_user(member.id, True, False)
		if member.id == message.author.id:
			await message.send(embed=discord.Embed(
				description="You aren't muted."
			))
		else:
			await message.send(embed=discord.Embed(
				description=f"<@{member.id}> isn't muted."
			))
	else:
		mute_str = seconds_to_string(mute_remaining)
		if member.id == message.author.id:
			await message.send(embed=discord.Embed(
				description=f'You are muted for {mute_str}'
			))
		else:
			await message.send(embed=discord.Embed(
				description=f'<@{member.id}> is muted for {mute_str}'
			))
Ejemplo n.º 5
0
async def run(message, member: Member = None):
	if message.channel.id not in {
		720073985412562975,  # gulag
		718076311150788649,  # bot-commands
		719518839171186698,  # staff-bot-commands
	}: return

	if not member:
		member = message.author

	mute_remaining = int((await db.get_mute_end(member.id)) - time.time())

	if mute_remaining < 0:
		await unmute_user(member.id, True, False)
		if member.id == message.author.id:
			await message.send(embed=discord.Embed(
				description="You aren't muted."
			))
		else:
			await message.send(embed=discord.Embed(
				description=f"<@{member.id}> isn't muted."
			))
	else:
		mute_str = seconds_to_string(mute_remaining)
		if member.id == message.author.id:
			await message.send(embed=discord.Embed(
				description=f'You are muted for {mute_str}'
			))
		else:
			await message.send(embed=discord.Embed(
				description=f'<@{member.id}> is muted for {mute_str}'
			))
Ejemplo n.º 6
0
async def run(message, member: Member = None):
    'Lists who you\'re subbed to.'
    if not member:
        # Default to the message author if the member is omitted
        member = message.author

    subs = await db.bobux_get_subscriptions(member.id)
    display_message = []
    total_spending = 0
    for sub in subs:
        receiver = sub['id']
        tier = sub['tier']
        tier_upper = tier.upper()
        next_payment_delta = sub['next_payment'] - datetime.utcnow()
        next_payment_seconds = next_payment_delta.total_seconds()
        next_payment_display = seconds_to_string(next_payment_seconds)
        display_message.append(
            f'<@{receiver}> - **{tier_upper}** (next payment in {next_payment_display})'
        )
        total_spending += tiers[tier]

    if member == message.author:
        title = 'Your subs'
    else:
        title = f'{member}\'s subs'

    title += f' ({total_spending} bobux spent per week)'

    await message.channel.send(embed=discord.Embed(
        title=title, description='\n'.join(display_message) or 'no subs'))
Ejemplo n.º 7
0
def add_attachment(attachment):
	msg = u""
	tpe = ""
	if attachment["type"] == "link":
		msg = u"{0}: {1}".format(attachment["link"]["title"], attachment["link"]["url"])
		tpe = _(u"Link")
	elif attachment["type"] == "photo":
		tpe = _(u"Photo")
		msg = attachment["photo"]["text"]
		if msg == "":
			msg = _(u"no description available")
	elif attachment["type"] == "video":
		msg = u"{0}".format(attachment["video"]["title"],)
		tpe = _(u"Video")
	elif attachment["type"] == "audio":
		msg = u"{0}".format(" ".join(session.compose_audio(attachment["audio"])))
		tpe = _(u"Audio")
	elif attachment["type"] == "doc":
		if attachment["doc"].has_key("preview") and attachment["doc"]["preview"].has_key("audio_msg"):
			tpe = _(u"Voice message")
			msg = utils.seconds_to_string(attachment["doc"]["preview"]["audio_msg"]["duration"])
		else:
			msg = u"{0}".format(attachment["doc"]["title"])
			tpe = _(u"{0} file").format(attachment["doc"]["ext"])
	return [tpe, msg]
Ejemplo n.º 8
0
async def run(message, member: Member = None):
    'Says who is subbed to you (or another member). Use !subs to see who you\'re subbed to.'
    if not member:
        member = message.author
    subs = await db.bobux_get_all_subscriptions(member.id)
    display_message = []
    total_earning = 0

    for sub in subs:
        sender = sub['sender']
        tier = sub['tier']
        tier_upper = tier.upper()
        next_payment_delta = sub['next_payment'] - datetime.utcnow()
        next_payment_seconds = next_payment_delta.total_seconds()
        next_payment_display = seconds_to_string(next_payment_seconds)
        display_message.append(
            f'<@{sender}> - **{tier_upper}** (next payment in {next_payment_display})'
        )
        total_earning += tiers[tier]

    if member == message.author:
        title = 'Your simps'
    else:
        title = f'{member}\'s simps'

    title += f' ({total_earning} bobux earnt per week)'

    await message.channel.send(embed=discord.Embed(
        title=title, description='\n'.join(display_message) or '*no simps*'))
Ejemplo n.º 9
0
async def do_mute(message, member, length, reason, muted_by: int=0):
	for infraction in await db.get_infractions(member.id):
		if datetime.utcnow() - infraction['date'] < timedelta(minutes=1):
			# if the infraction was made less than 3 minutes ago, it should be removed as it was likely an accident
			await db.clear_infraction(infraction['_id'])

	await db.add_infraction(
		member.id,
		'mute',
		reason,
		length,
		muted_by
	)
	
	mute_length_string = seconds_to_string(length)

	try:
		if reason:
			await member.send(f'You were muted for {mute_length_string} for "**{reason}**"')
		else:
			await member.send(f'You were muted for {mute_length_string}')
	except discord.errors.Forbidden:
		pass

	try:
		await mute_user(
			member,
			length,
			message.guild.id if message.guild else None
		)
	except discord.errors.Forbidden:
		await message.send("I don't have permission to do this")
Ejemplo n.º 10
0
	def load_audios(self):
		for i in self.post:
			s = u"{0} - {1}. {2}".format(i["title"], i["artist"], utils.seconds_to_string(i["duration"]))
			self.dialog.insert_audio(s)
		self.dialog.list.SetSelection(0)
		if len(self.post) == 1:
			self.dialog.list.Enable(False)
			self.dialog.title.SetFocus()
Ejemplo n.º 11
0
	def fill_information(self):
		if self.post.has_key("artist"):
			self.dialog.set("artist", self.post["artist"])
		if self.post.has_key("title"):
			self.dialog.set("title", self.post["title"])
		if self.post.has_key("duration"):
			self.dialog.set("duration", utils.seconds_to_string(self.post["duration"]))
		self.dialog.set_title(u"{0} - {1}".format(self.post["title"], self.post["artist"]))
		call_threaded(self.get_lyrics)
Ejemplo n.º 12
0
	def fill_information(self, index):
		post = self.post[index]
		if post.has_key("artist"):
			self.dialog.set("artist", post["artist"])
		if post.has_key("title"):
			self.dialog.set("title", post["title"])
		if post.has_key("duration"):
			self.dialog.set("duration", utils.seconds_to_string(post["duration"]))
		self.dialog.set_title(u"{0} - {1}".format(post["title"], post["artist"]))
		call_threaded(self.get_lyrics)
		if  post["owner_id"] == self.session.user_id or self.added_audios.has_key(post["id"]) == True:
			self.dialog.change_state("remove", True)
			self.dialog.change_state("add", False)
		else:
			self.dialog.change_state("add", True)
			self.dialog.change_state("remove", False)
Ejemplo n.º 13
0
async def run(message,
              member: Member,
              mute_length: Time = Time(0),
              reason: str = None):
    'Changes the mute length of a user without adding a new infraction'

    if not member or not mute_length:
        return await message.channel.send(
            'Invalid command usage. Example: **!editmute gogourt 10 years accidentally entered a length that was too short**'
        )

    if reason:
        reason = reason.strip()

    mute_length_string = seconds_to_string(mute_length)

    if reason:
        changed_message = f'<@{member.id}>\'s mute has been changed to {mute_length_string} for "**{reason}**"'
        dm_changed_message = f'Your mute has been extended to {mute_length_string} for "**{reason}**"'
    else:
        changed_message = f'<@{member.id}>\'s mute has been changed to {mute_length_string}'
        dm_changed_message = f'Your mute has been extended to {mute_length_string}'

    mute_remaining = int((await db.get_mute_end(member.id)) - time.time())

    if mute_remaining < 0:
        return await message.channel.send('That user isn\'t muted')
    else:
        try:
            await member.send(dm_changed_message)
        except discord.errors.Forbidden:
            pass

        await message.send(embed=discord.Embed(description=changed_message))

        await do_mute(message,
                      member,
                      mute_length,
                      reason,
                      muted_by=message.author.id)
Ejemplo n.º 14
0
async def run(message, member: Member, reason: str = None):
    'Automatically guess the mute length from the reason, and past infractions'

    if not member or not reason:
        return await message.channel.send(
            'Invalid command usage. Example: **!mute gogourt 10 years nerd**')

    if reason:
        reason = reason.strip()

    mute_length = await guess_mute_length_for_member(member, reason)
    mute_length_string = seconds_to_string(mute_length)

    mute_message = f'<@{member.id}> has been muted for {mute_length_string} for "**{reason}**".'

    await message.send(embed=discord.Embed(description=mute_message))

    await do_mute(message,
                  member,
                  mute_length,
                  reason,
                  muted_by=message.author.id)
Ejemplo n.º 15
0
def compose_video(video, session=None):
	if video == False: return [_(u"Audio removed from library"), "", ""]
	return [video["title"], video["description"], utils.seconds_to_string(video["duration"])]
Ejemplo n.º 16
0
def compose_audio(audio, session=None):
	if audio == False: return [_(u"Audio removed from library"), "", ""]
	return [audio["title"], audio["artist"], utils.seconds_to_string(audio["duration"])]
Ejemplo n.º 17
0
async def duel_wait_for(client, channel, opponent_1, opponent_2):
	global duel_statuses

	def duel_check(message):
		print(message.content.strip())
		return (
			message.author.id in {opponent_1.id, opponent_2.id}
			and message.content in {'🔫', ':gun:'}
		)
	try:

		message = await client.wait_for('message', check=duel_check, timeout=60)
	except asyncio.TimeoutError:
		if opponent_1.id in active_duelers:
			active_duelers.remove(opponent_1.id)
		if opponent_2.id in active_duelers:
			active_duelers.remove(opponent_2.id)
		return
	duel_id = get_duel_id(opponent_1, opponent_2)
	duel_at_zero = duel_statuses[duel_id]['zero']
	duel_statuses[duel_id]['ended'] = True
	rigged = False

	opponent_1_active_pet = await get_active_pet(opponent_1.id)
	opponent_2_active_pet = await get_active_pet(opponent_2.id)

	# "Gladiator" gladiator pet ability
	if opponent_1_active_pet and opponent_1_active_pet.id == 'gladiator':
		if random.random() >= .9:
			rigged_duel_users.add(opponent_1.id)
	if opponent_2_active_pet and opponent_2_active_pet.id == 'gladiator':
		if random.random() >= .9:
			rigged_duel_users.add(opponent_2.id)

	if duel_at_zero:
		duel_winner: Union[Member] = message.author
		duel_loser = opponent_1 if duel_winner == opponent_2 else opponent_2
		if duel_loser.id in rigged_duel_users:
			rigged_duel_users.remove(duel_loser.id)
			duel_winner_tmp = duel_winner
			duel_winner = duel_loser
			duel_loser = duel_winner_tmp
			rigged = True
		await channel.send(f'<@{duel_winner.id}> won the duel!')
	else:
		duel_winner = opponent_1 if message.author == opponent_2 else opponent_2
		duel_loser = opponent_1 if duel_winner == opponent_2 else opponent_2
		if duel_loser.id in rigged_duel_users:
			rigged_duel_users.remove(duel_loser.id)
			duel_winner_tmp = duel_winner
			duel_winner = duel_loser
			duel_loser = duel_winner_tmp
			rigged = True

		await channel.send(f'<@{duel_winner.id}> won the duel because <@{duel_loser.id}> shot too early')
	if channel.id == 750147192383078400:  # quaglet channel
		mute_length = 0
	elif channel.id == config.channels['general']:  # general
		mute_length: int = 60 * 15

		winner_active_pet = await get_active_pet(duel_winner.id)

		# "Harder blows" gladiator pet ability
		if winner_active_pet and winner_active_pet.id == 'gladiator':
			mute_length = int(mute_length * 1.5)

		mute_length_string = seconds_to_string(mute_length)

		try: await duel_loser.send(f'You were muted for {mute_length_string} because you lost a duel in general')
		except: pass

		# increase the winstreak of the winner
		last_dueled_member_id = await db.fetch_last_dueled_member(duel_winner.id)

		await db.set_last_dueled_member(duel_loser.id, duel_winner.id)
		await db.set_last_dueled_member(duel_winner.id, duel_loser.id)
		# reset the winstreak of the loser
		await db.reset_duel_winstreak(duel_loser.id)

		# make sure the last person the winner dueled was someone different
		if last_dueled_member_id != duel_loser.id:
			await db.increase_duel_winstreak(duel_winner.id)

			winstreak = await db.fetch_duel_winstreak(duel_winner.id)
			if winstreak == 1:
				await db.change_bobux(duel_winner.id, 20)
			elif winstreak == 2:
				await db.change_bobux(duel_winner.id, 50)
			elif winstreak == 3:
				await db.change_bobux(duel_winner.id, 100)
			elif winstreak >= 4:
				await db.change_bobux(duel_winner.id, 200)
				await give_unique_pet(duel_winner, 'gladiator')

	elif channel.id == config.channels.get('gulag'):  # gulag
		mute_end = await db.get_mute_end(duel_loser.id)
		mute_remaining = int(mute_end - time.time())
		mute_length = mute_remaining + 60 * 5
	else:
		mute_length = 60 * 1
		try:
			await duel_loser.send('You were muted for one minute because you lost a duel')
		except discord.errors.Forbidden:
			pass
		except AttributeError:
			pass
	try:
		del duel_statuses[duel_id]
	except KeyError:
		pass
	if opponent_1.id in active_duelers:
		active_duelers.remove(opponent_1.id)
	if opponent_2.id in active_duelers:
		active_duelers.remove(opponent_2.id)

	if mute_length > 0:
		await mute_user(
			duel_loser,
			mute_length,
			channel.guild.id if channel.guild else None
		)

	if not rigged and duel_loser.id == message.guild.me.id and channel.id == config.channels.get('general'):
		print('won in general!', duel_winner.id)
		# if you win against forum sweats in general, you get 50 bobux
		await db.change_bobux(duel_winner.id, 50)
		print('epic gaming moment')
Ejemplo n.º 18
0
def upload_manager():
    global config, default_check_interval
    try:
        default_check_interval = config['local_folder_check_interval']
        logger.debug("Started upload manager for %r", config['local_folder'])
        while True:
            time.sleep(60 * config['local_folder_check_interval'])

            # restore check interval to original after an extended sleep after a rate limit ban (25hrs)
            if config['local_folder_check_interval'] == 1500:
                config['local_folder_check_interval'] = default_check_interval
                logger.info(
                    "Restored local_folder_check_interval to %d minutes after an extended sleep (25 hours) due "
                    "to the last upload being cancelled due to rate limits!",
                    config['local_folder_check_interval'])
                if config['pushover_app_token'] and config[
                        'pushover_user_token']:
                    utils.send_pushover(
                        config['pushover_app_token'],
                        config['pushover_user_token'],
                        "local_folder_check_interval has been reset back to %d minutes after a 25 hour "
                        "sleep due to ratelimits!" %
                        config['local_folder_check_interval'])

            logger.debug("Checking size of %r", config['local_folder'])
            size = utils.folder_size(config['local_folder'],
                                     config['du_excludes'])
            if size is not None and size > 0:
                if size >= config['local_folder_size']:
                    logger.debug("Local folder has %d gigabytes, %d too many!",
                                 size, size - config['local_folder_size'])

                    # check if files are opened, skip this upload if so
                    opened_files = utils.opened_files(config['local_folder'],
                                                      config['lsof_excludes'])
                    if opened_files:
                        for item in opened_files:
                            logger.debug("File is being accessed: %r", item)
                        logger.debug(
                            "Local folder has %d file(s) open, skipping upload until next check...",
                            len(opened_files))
                        # send skip notification
                        if config['pushover_app_token'] and config[
                                'pushover_user_token']:
                            utils.send_pushover(
                                config['pushover_app_token'],
                                config['pushover_user_token'],
                                "Upload process of %d gigabytes temporarily skipped.\n"
                                "%d file(s) are currently being accessed." %
                                (size, len(opened_files)))
                        continue

                    # remove hidden before upload
                    # (we don't want to delete a hidden from remote, after already replacing it)
                    logger.debug("Purging _HIDDEN~ before upload commences")
                    remove_hidden()

                    # send start notification
                    if config['pushover_app_token'] and config[
                            'pushover_user_token']:
                        utils.send_pushover(
                            config['pushover_app_token'],
                            config['pushover_user_token'],
                            "Upload process started. %d gigabytes to upload." %
                            size)

                    # rclone move local_folder to local_remote
                    logger.debug("Moving data from %r to %r...",
                                 config['local_folder'],
                                 config['local_remote'])
                    upload_cmd = utils.rclone_move_command(
                        config['local_folder'], config['local_remote'],
                        config['rclone_transfers'], config['rclone_checkers'],
                        config['rclone_bwlimit'], config['rclone_excludes'],
                        config['rclone_chunk_size'], config['dry_run'])
                    logger.debug("Using: %r", upload_cmd)

                    start_time = timeit.default_timer()
                    utils.run_command(upload_cmd, config)
                    time_taken = timeit.default_timer() - start_time
                    logger.debug("Moving finished in %s",
                                 utils.seconds_to_string(time_taken))

                    # remove empty directories
                    if len(config['rclone_remove_empty_on_upload']):
                        time.sleep(5)
                        utils.remove_empty_directories(config)

                    new_size = utils.folder_size(config['local_folder'],
                                                 config['du_excludes'])
                    logger.debug("Local folder is now left with %d gigabytes",
                                 new_size)

                    # send finish notification
                    if config['pushover_app_token'] and config[
                            'pushover_user_token']:
                        utils.send_pushover(
                            config['pushover_app_token'],
                            config['pushover_user_token'],
                            "Upload process finished in %s. %d gigabytes left over."
                            % (utils.seconds_to_string(time_taken), new_size))

                else:
                    logger.debug(
                        "Local folder is still under the max size by %d gigabytes",
                        config['local_folder_size'] - size)

    except Exception as ex:
        logger.exception("Exception occurred: ")
Ejemplo n.º 19
0
async def run(message, length: Time):
    'Debugging command seconds_to_string test time'
    await message.send(seconds_to_string(length))
Ejemplo n.º 20
0
def compose_audio(audio, session):
	return [audio["title"], audio["artist"], utils.seconds_to_string(audio["duration"])]