Skip to content

Instantly share code, notes, and snippets.

@dudanogueira
Created May 30, 2023 13:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dudanogueira/588dd4649fe77878f04e1e2f84cc4112 to your computer and use it in GitHub Desktop.
Save dudanogueira/588dd4649fe77878f04e1e2f84cc4112 to your computer and use it in GitHub Desktop.
Rocket.Chat Python script to delete visitors with the term guest
import requests
import json
# Set up the Rocket.Chat API endpoint and credentials
API_URL = 'http://localhost:3000'
USERNAME = 'adminrc'
PASSWORD = 'admin'
def get_auth_token():
# Get the authentication token
auth_data = {
'user': USERNAME,
'password': PASSWORD
}
response = requests.post(f'{API_URL}/api/v1/login', data=auth_data)
if response.status_code == 200:
return response.json().get('data').get('authToken'), response.json().get('data').get('userId')
else:
raise Exception('Failed to retrieve authentication token')
def get_visitors():
# Get the list of visitors from Rocket.Chat
auth_token, userId = get_auth_token()
headers = {
'X-Auth-Token': auth_token,
'X-User-Id': userId
}
response = requests.get(
f'{API_URL}/api/v1/livechat/visitors.search?term=guest', headers=headers)
if response.status_code == 200:
visitors = response.json().get('visitors')
visitors_token = []
for visitor in visitors:
# get visitor_id
visitor = requests.get(
f'{API_URL}/api/v1/livechat/visitors.info?visitorId=' + visitor["_id"], headers=headers)
visitors_token.append(visitor.json()["visitor"])
return visitors_token
else:
raise Exception('Failed to retrieve visitors')
def delete_visitor(visitor_id):
# Delete a visitor by their ID
auth_token = get_auth_token()
headers = {
'X-Auth-Token': auth_token,
'X-User-Id': 'me'
}
print("will deleting", visitor_id)
response = requests.delete(f'{API_URL}/api/v1/livechat/visitor/{visitor_id}')
if response.status_code != 200:
raise Exception(f'Failed to delete visitor with ID: {visitor_id}')
else:
print("DELETED!!!")
def delete_guest_visitors():
# Delete visitors whose usernames contain the term "guest"
visitors = get_visitors()
print("FOUND VISITORS: ", visitors)
for visitor in visitors:
print("##### PROCESS:", visitor)
username = visitor.get("username")
if 'guest' in username:
visitor_id = visitor.get('token')
delete_visitor(visitor_id)
print(f'Deleted visitor with username: {username}')
# Call the delete_guest_visitors function to initiate the deletion
delete_guest_visitors()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment