예제 #1
0
def find_incidents_job():
	for domain in config['domains']:
		incidents = [i for i in pd.fetch_incidents(api_key=domain['token']) if i['service']['id'] in domain['services']]
		for incident in incidents:
			created = parse(incident['created_at'])
			service = incident['service']['id']

			if not incident['id'] in current_incidents:
				current_incidents[incident['id']] = {
					"id": incident['id'],
					"status": incident['status'],
					"summary": incident['summary'],
					"domain": domain
				}

			if incident['status'] == "triggered":
				if 'should_resolve' in current_incidents[incident['id']]:
					del current_incidents[incident['id']]['should_resolve']
				if not 'should_ack' in current_incidents[incident['id']]:
					print(f"Found triggered incident {incident['summary']} ({incident['id']}), created at {created}")
					min_ack_duration = Duration(domain['services'][service]['ack']['min'])
					max_ack_duration = Duration(domain['services'][service]['ack']['max'])
					ack_seconds = randint(min_ack_duration.to_seconds(), max_ack_duration.to_seconds())
					current_incidents[incident['id']]['should_ack'] = created + timedelta(seconds=ack_seconds)
					print(f"  Will acknowledge incident {incident['id']} at {current_incidents[incident['id']]['should_ack']}")
			elif incident['status'] == "acknowledged":
				if 'should_ack' in current_incidents[incident['id']]:
					del current_incidents[incident['id']]['should_ack']
				if not 'should_resolve' in current_incidents[incident['id']]:
					print(f"Found acknowledged incident {incident['summary']} ({incident['id']}), created at {created}")
					min_res_duration = Duration(domain['services'][service]['resolve']['min'])
					max_res_duration = Duration(domain['services'][service]['resolve']['max'])
					res_seconds = randint(min_res_duration.to_seconds(), max_res_duration.to_seconds())
					current_incidents[incident['id']]['should_resolve'] = created + timedelta(seconds=res_seconds)
					print(f"  Will resolve incident {incident['id']} at {current_incidents[incident['id']]['should_resolve']}")

		for k, v in dict(current_incidents).items():
			if 'should_ack' in v and v['should_ack'] < datetime.datetime.utcnow().replace(tzinfo=dateutil.tz.tzutc()):
				print(f"Should ack incident {v['summary']} ({k})")
				acknowledge(v)
			elif 'should_resolve' in v and v['should_resolve'] < datetime.datetime.utcnow().replace(tzinfo=dateutil.tz.tzutc()):
				print(f"Should resolve incident {v['summary']} ({k})")
				resolve(v)
예제 #2
0
 async def mute(self,
                ctx,
                target: discord.Member = None,
                duration=None,
                *,
                reason=None):
     if target is None:
         return await ctx.send("Specify a user to mute")
     if duration is None:
         return await ctx.send("Specify a duration")
     allowed = await self.check_hierarchy(ctx, ctx.message.author, target)
     if not allowed:
         return await self.ctx.send(
             "You don't have permission to mute that user")
     if target not in ctx.guild.members:
         return await ctx.send("User is not in guild")
     duration_pre_parse = duration
     try:
         duration = Duration(duration)
         duration = duration.to_seconds()
     except:
         return await ctx.send("Invalid duration")
     infraction_id = await self.generate_infraction_id()
     notified = await self.notify_target(ctx,
                                         target=target,
                                         infraction_type="mute",
                                         reason=reason,
                                         infraction_id=infraction_id,
                                         duration=duration_pre_parse)
     try:
         mute_role = discord.utils.get(ctx.guild.roles,
                                       id=self.config.mute_role)
     except:
         return await ctx.send("Invalid mute role, yell at waffles")
     try:
         await target.add_roles(
             mute_role,
             reason=f"Action by {ctx.message.author} for {reason}")
     except:
         await ctx.send("Error muting user")
     await self.log_infraction(ctx,
                               verb="muted",
                               target=target,
                               mod=ctx.message.author,
                               reason=reason,
                               infraction_type="mute",
                               notified=notified,
                               infraction_id=infraction_id,
                               duration=duration_pre_parse)
     await self.store_infraction(ctx,
                                 infraction_id=infraction_id,
                                 infraction_type="mute",
                                 target=target,
                                 mod=ctx.message.author,
                                 reason=reason,
                                 duration=duration_pre_parse)
     await self.confirm_infraction(ctx,
                                   verb="muted",
                                   target=target,
                                   infraction_id=infraction_id)
     await asyncio.sleep(duration)
     await target.remove_roles(
         mute_role, reason=f"Temporary mute {infraction_id} expired")
     notified = await self.notify_target(
         ctx,
         target=target,
         infraction_type="unmute",
         reason=f"Temporary mute {infraction_id} expired")
     await self.log_infraction(
         ctx,
         verb="unmuted",
         target=target,
         mod=ctx.message.author,
         reason=f"Temporary mute {infraction_id} expired",
         infraction_type="unmute",
         notified=notified)
예제 #3
0
async def timed_restriction(m: types.Message,
                            user: dict,
                            chat: dict,
                            action='ban'):
    try:
        user_request = await bot.get_chat_member(chat['id'], m.from_user.id)
    except:
        await m.reply('Не могу получить информацию о юзере.')
        return
    if not (user_request.can_restrict_members
            or user_request.status == 'creator' or user.get('status', 0) >= 3):
        return await m.reply('Ты куда лезишь?')

    chat_id = chat['id']
    target_user_id = m.reply_to_message.from_user.id
    ban_user = m.reply_to_message.from_user.to_python()
    log_event = LogEvents.TEMPBAN if action == 'ban' else LogEvents.UNMEDIA

    until_date = None

    command, _, msg_args = m.text.partition(' ')
    if msg_args:
        time_tokens, other_tokens = get_time_args(msg_args)
        time_string = ''.join(time_tokens)
        if not time_tokens:
            now = datetime.utcnow().replace()
            until_date = get_next_day_msk().astimezone(
                pytz.utc)  # 21:00 UTC, 00:00 MSK
            time_string = f"{(until_date.replace(tzinfo=None) - now).total_seconds()}s"
    else:
        other_tokens = None
        now = datetime.utcnow()
        until_date = get_next_day_msk().astimezone(
            pytz.utc)  # 21:00 UTC, 00:00 MSK
        time_string = f"{(until_date.replace(tzinfo=None) - now).total_seconds()}s"

    if valid_duration(time_string):
        duration = Duration(time_string)

        ban_seconds = duration.to_seconds()
        # Чтобы без пермачей
        if ban_seconds <= 30:
            ban_seconds = 31
        if ban_seconds > 31_536_000:
            ban_seconds = 31_536_000 - 1
        human_time = format_seconds(ban_seconds)
        try:
            await bot.restrict_chat_member(
                chat_id,
                target_user_id,
                until_date=until_date if until_date else timedelta(
                    seconds=ban_seconds),
                can_send_messages=action != 'ban',
                can_send_media_messages=False,
                can_send_other_messages=False,
                can_add_web_page_previews=False)
        except Exception as e:
            return await m.reply('штото пошло не так :((')
        kb = types.InlineKeyboardMarkup()
        kb.add(
            types.InlineKeyboardButton('Unban',
                                       callback_data=unban_cb.new(
                                           chat_id=str(chat['id']),
                                           user_id=str(ban_user['id']))))
        await add_log(chat_id, target_user_id, log_event, by=m.from_user.id)

        text_kwargs = {'duration': human_time}
        if other_tokens:
            text_kwargs['reason'] = ' '.join(other_tokens)

        await log(event=log_event,
                  chat=chat,
                  user=ban_user,
                  message_id=m.message_id,
                  admin=user,
                  text_kwargs=text_kwargs,
                  log_kwargs={'reply_markup': kb})
        await mp.track(m.from_user.id, StatsEvents.TEMPBAN, m)

        await m.reply(
            get_restrict_text(chat, action,
                              till_next_day=bool(until_date)).format(
                                  human_time=hbold(human_time)))
    else:
        return await m.reply('Я такие даты не понимаю')