Last active
August 3, 2023 19:18
-
-
Save erickdsama/10d7e77cb8d5f138ed1cea43d79b3092 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
import os | |
from bs4 import BeautifulSoup | |
from requests import Session | |
session = Session() | |
from requests import post | |
name_key_chat = { | |
"STEVE": "123456789123456789", | |
"JULIO": "123456789123456789", | |
"NAHUEL": "123456789123456789", | |
"SERGIO": "123456789123456789", | |
"ERICK": "123456789123456789", | |
"all": "all" | |
} | |
TIME_RANGES = { | |
"0": 4, | |
"1": 2, | |
"2": 1, | |
"3": 0.5 | |
} | |
URL_SUPPORT = '' | |
SPACE = os.getenv('SPACE', 'AAAAKz4J29g') | |
USERNAME = os.getenv('SUPPORT_USER', '') | |
PASSWORD = os.getenv('SUPPORT_PASS', '') | |
G_CHAT_KEY = os.getenv('G_CHAT_KEY', '') | |
G_CHAT_TOKEN = os.getenv('G_CHAT_TOKEN', '') | |
class GoogleChat(object): | |
""" Hangouts Chat incoming webhook. """ | |
def __init__(self): | |
""" | |
room_webhooks: dict[identifier_room:list[chat rooms webhook urls]] | |
This is useful for register chat rooms for send data to webhooks | |
""" | |
self.headers = {'Content-Type': 'application/json'} | |
self.room_webhooks = { | |
'dev-alerts': [f'https://chat.googleapis.com/v1/spaces/{SPACE}/messages?key={G_CHAT_KEY}&token={G_CHAT_TOKEN}'], | |
} | |
def notify(self, room_name: str, message) -> None: | |
for url in self.room_webhooks[room_name]: | |
try: | |
response = post(url=url, headers=self.headers, data=json.dumps({'text': str(message)})) | |
except (ConnectionError, TypeError) as error: | |
print(f"Request to Google returned an error {error}") | |
def save_current_state(data): | |
with open('data.json', 'w') as d: | |
d.write(json.dumps(data)) | |
def update_state(new_data): | |
try: | |
json_data = read_state() | |
for id_, ticket_ in new_data.items(): | |
json_data[id_].update(ticket_) | |
save_current_state(json_data) | |
except Exception: | |
print(f"error {e}") | |
save_current_state(new_data) | |
def read_state(): | |
try: | |
with open('data.json', 'r') as data: | |
json_data = json.loads(data.read()) | |
return json_data | |
except Exception: | |
return {} | |
def login_support_page(): | |
response = session.get(f'{URL_SUPPORT}/index.php') | |
html_content = response.content.decode('utf-8') | |
soup = BeautifulSoup(html_content) | |
csrf_input = soup.find('input', attrs={'name': '_glpi_csrf_token'}) | |
name_input = soup.find('input', attrs={'id': 'login_name'}) | |
pass_input = soup.find('input', attrs={'type': 'password'}) | |
key_name = name_input.get('name') | |
key_password = pass_input.get('name') | |
token = csrf_input.get('value') | |
data = {key_name: USERNAME, key_password: PASSWORD, '_glpi_csrf_token': token} | |
response = session.post(f'{URL_SUPPORT}/front/login.php', data=data) | |
response = session.get(f'{URL_SUPPORT}/front/ticket.php') | |
def parse_tickets_page(soup): | |
massive_form = soup.find('form', attrs={'id': 'massformTicket'}) | |
table = massive_form.find('table') | |
tbody = table.find('tbody') | |
rows = tbody.find_all('tr') | |
tickets = {} | |
for row in rows: | |
cols = row.find_all('td') | |
# link | |
col = cols[2] | |
link_tag = col.find('a') | |
ticket_link = link_tag.get('href') | |
ticket_name = link_tag.text | |
# id | |
col = cols[1] | |
span = col.find('span') | |
ticket_id = span.text | |
# class="text-nowrap" 2023-08-01 15:34 | |
# status | |
col = cols[3] | |
icon = col.find('i') | |
ticket_status = icon.get('title') | |
# created date | |
col = cols[5] | |
span = col.find('span') | |
ticket_created = span.text | |
# asignado a | |
col = cols[8] | |
ticket_link_tag = col.find('a') | |
ticket_assigned = ticket_link_tag.previous_sibling | |
tickets[ticket_id] = { | |
'id': ticket_id, | |
'name': ticket_name, | |
'created': ticket_created, | |
'link': ticket_link, | |
'status': ticket_status, | |
"assigned": ticket_assigned, | |
} | |
update_state(tickets) | |
return tickets | |
def validate_notification(ticket): | |
from datetime import datetime, timedelta | |
now_date = datetime.now() | |
datetime_str = ticket.get("created") | |
if "planificada" in ticket.get("status"): | |
return False | |
if not ticket.get('last_read'): | |
last_read = now_date.strftime('%Y-%m-%d %H:%M') | |
ticket['last_read'] = last_read | |
update_state({ticket["id"]: ticket}) | |
return True | |
last_read = ticket.get("last_read", now_date.strftime('%Y-%m-%d %H:%M')) | |
created_date = datetime.strptime(datetime_str, "%Y-%m-%d %H:%M") | |
last_read_date = datetime.strptime(last_read, "%Y-%m-%d %H:%M") | |
delta_ = now_date - created_date | |
print("*"* 20) | |
print(f"ticket {ticket['name']}") | |
time_range = TIME_RANGES.get(str(delta_.days), 0.5) | |
next_alert = now_date + timedelta(hours=time_range) | |
print(f"Next Alert: {next_alert}", ) | |
print("\n") | |
difference_now_last_send = (now_date - last_read_date).seconds / 60 / 60 | |
print(f"Elapsed time: {difference_now_last_send:.2f} Hour(s)") | |
if difference_now_last_send > time_range: | |
last_read = now_date.strftime('%Y-%m-%d %H:%M') | |
ticket['last_read'] = last_read | |
update_state({ticket["id"]: ticket}) | |
return True | |
return False | |
def send_to_google_chat(): | |
tickets = read_state() | |
for _id, ticket in tickets.items(): | |
if not validate_notification(ticket): | |
continue | |
key_name = "all" | |
for name, key in name_key_chat.items(): | |
if name in ticket.get('assigned'): | |
key_name = key | |
build_message = f"\n🎫 Hay un ticket para: <users/{key_name}>.\n\n<f'{URL_SUPPORT}{ticket.get('link')}|{ticket.get('name')}>\n*{ticket.get('status')}*\n\n" | |
GoogleChat().notify(room_name='dev-alerts', message=build_message) | |
def tickets_page(): | |
response = session.get(f'{URL_SUPPORT}/front/ticket.php') | |
html_content = response.content.decode('utf-8') | |
soup = BeautifulSoup(html_content) | |
search_form = soup.find('form', attrs={'name': 'searchformticket'}) | |
csrf_input = search_form.find('input', attrs={'name': '_glpi_csrf_token'}) | |
token = csrf_input.get('value') | |
params = { | |
"action": "display_results", | |
"searchform_id": "search_1665143946", | |
"itemtype": "Ticket", | |
"glpilist_limit": "15", | |
"sort[]": "19", | |
"order[]": "DESC", | |
"criteria[1][link]": "AND", | |
"criteria[1][field]": "8", | |
"criteria[1][searchtype]": "equals", | |
"criteria[1][value]": "63", | |
"criteria[2][link]": "AND NOT", | |
"criteria[2][field]": "12", | |
"criteria[2][searchtype]": "equals", | |
"criteria[2][value]": "old", | |
"_glpi_csrf_token": f"{token}", | |
} | |
response = session.get(f'{URL_SUPPORT}/front/ticket.php', params=params) | |
html_content = response.content.decode('utf-8') | |
soup = BeautifulSoup(html_content) | |
return parse_tickets_page(soup) | |
login_support_page() | |
tickets_page() | |
send_to_google_chat() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment