Skip to content
This repository has been archived by the owner on Feb 14, 2023. It is now read-only.

Commit

Permalink
Merge branch 'master' of github.com:Vyxal/VyxalBotSE
Browse files Browse the repository at this point in the history
  • Loading branch information
hyper-neutrino committed Jul 17, 2021
2 parents 1db82a1 + 81b0cfe commit 77b9134
Show file tree
Hide file tree
Showing 5 changed files with 156 additions and 124 deletions.
1 change: 1 addition & 0 deletions README.md
@@ -0,0 +1 @@
**Do not commit changes directly to this branch. Create a new branch and open a pull request so @hyper-neutrino can review the changes first.**
Binary file modified __pycache__/chatbot.cpython-38.pyc
Binary file not shown.
24 changes: 17 additions & 7 deletions bot.py
Expand Up @@ -11,26 +11,29 @@
secret = f.read().strip()

hooks = {}

def handler(room):
def _inner(activity):
if room != rid: return
if "e" in activity:
for x in activity["e"]:
if x["user_id"] == 281362 and x["content"] == "!!/swap-rooms":
print(x)
if x["user_id"] == 281362 and x.get("content") == "!!/swap-rooms":
send("I am now leaving this room. Goodbye!")
swap()
send("Hello! I am now operating in this room.")

if x["event_type"] == 1 and x["room_id"] == room:
if x["user_id"] == 296403: return
if x["user_id"] == 296403: continue
try:
r = requests.post("http://localhost:5666/msg", headers = {"Content-Type": "application/json"}, json = {"secret": secret, "message": x})
if r.status_code == 200 and r.text:
hooks[x["message_id"]] = send(r.text)
except:
traceback.print_exc()
elif x["event_type"] == 2 and x["room_id"] == room:
if x["user_id"] == 296403: return

if x["event_type"] == 2 and x["room_id"] == room:
if x["user_id"] == 296403: continue
try:
r = requests.post("http://localhost:5666/msg", headers = {"Content-Type": "application/json"}, json = {"secret": secret, "message": x})
if r.status_code == 200 and r.text:
Expand All @@ -40,8 +43,15 @@ def _inner(activity):
hooks[x["message_id"]] = send(r.text)
except:
traceback.print_exc()
elif x["event_type"] == 10 and x["room_id"] == room:
if x["user_id"] == 296403: return

if x["event_type"] == 3 and x["room_id"] == room:
if x["user_id"] == 296403: continue
r = requests.post("http://localhost:5666/join", headers = {"Content-Type": "application/json"}, json = {"secret": secret, "data": x})
if r.status_code == 200 and r.text:
send(r.text)

if x["event_type"] == 10 and x["room_id"] == room:
if x["user_id"] == 296403: continue
if x["message_id"] in hooks:
rooms[rid].deleteMessage(hooks[x["message_id"]])
return _inner
Expand Down
44 changes: 22 additions & 22 deletions chatbot.py
Expand Up @@ -54,7 +54,7 @@
#34: 'Unknown',

}


# useful functions
def log(msg, name="../logs/log.txt",verbose=True): # Logging messages and errors | Appends <msg> to the log <name>, prints if verbose
Expand Down Expand Up @@ -134,13 +134,13 @@ def __init__(self, room_id, chatbot, onActivity):
self.id=room_id # room identifier
self.chatbot=chatbot # parent chatbot
self.onActivity=onActivity # callback for events

#initialize vars
self.thread=None # own thread
self.running=False # currently running ?
self.ws=None # WebSocket
self.temp_path="{}/temp".format(self.id)

# initialize
self.connect_ws() # attempt to connect via WebSockets
if not os.path.exists("{}".format(self.id)):
Expand All @@ -150,7 +150,7 @@ def __init__(self, room_id, chatbot, onActivity):

def __repr__(self):
return 'Room(id = {})'.format(self.id)

def connect_ws(self):
payload={"fkey": self.chatbot.fkey,'roomid': self.id}
try:
Expand All @@ -163,7 +163,7 @@ def connect_ws(self):
self.thread = threading.Thread(target=self.run)
#self.thread.setDaemon(True)
self.thread.start()

def run(self):
self.running=True
while self.running:
Expand All @@ -181,12 +181,12 @@ def run(self):
self.handleActivity(a)
except:
pass

def leave(self):
log("Left room {}".format(self.id))
self.running=False
self.chatbot.rooms_joined.remove(self)

def handleActivity(self, activity):
log('Got activity {}'.format(activity), verbose=False)
self.onActivity(activity)
Expand All @@ -197,7 +197,7 @@ def handleActivity(self, activity):
if event['event_type'] > 2:
log('Event: ' + EVENTS[event['event_type']])
log('Event details: ' + str(event))

def sendMessage(self, msg, wait=False):
if not wait: log(msg)
payload = {"fkey": self.chatbot.fkey, "text": msg}
Expand All @@ -212,23 +212,23 @@ def sendMessage(self, msg, wait=False):
r = r.json()
# log(r)
return r["id"]

def editMessage(self, msg, msg_id): # edit message with id <msg_id> to have the new content <msg>
payload = {"fkey": self.chatbot.fkey, "text": msg}
headers = {'Referer': "http://chat.stackexchange.com/rooms/{}".format(self.id)}
r = self.chatbot.sendRequest("http://chat.stackexchange.com/messages/{}".format(msg_id), "post", payload, headers).text
if r.find("You can perform this action again") >= 0:
time.sleep(3)
self.editMessage(msg, msg_id)

def deleteMessage(self, msg_id): # delete message with id <msg_id>
payload = {"fkey": self.chatbot.fkey}
headers = {'Referer': "http://chat.stackexchange.com/rooms/{}".format(self.id)}
r = self.chatbot.sendRequest("http://chat.stackexchange.com/messages/{}/delete".format(msg_id), "post", payload, headers).text
if r.find("You can perform this action again") >= 0:
time.sleep(3)
self.deleteMessage(msg_id)

# main class
class Chatbot():
def __init__(self, decrypt = None, verbose=True):
Expand All @@ -239,10 +239,10 @@ def __init__(self, decrypt = None, verbose=True):
self.rooms_joined=[]
self.host=None
self.decrypt_key = decrypt

# propagate vars
self.verbose=verbose

def sendRequest(self, url, typeR="get", payload={}, headers={},verify=True): # sends a POST/GET request to <url> with arguments <payload>, headers <headers>. Will check SSL if <verify>.
r = ""
successful, tries = False, 0
Expand All @@ -264,10 +264,10 @@ def sendRequest(self, url, typeR="get", payload={}, headers={},verify=True): # s
return False
tries += 1
return r

def log(self, msg, name="../logs/log.txt"): # Logging messages and errors | Appends <msg> to the log <name>, prints if self.verbose
log(msg,name,verbose=self.verbose)

def login(self, host="codegolf.stackexchange.com"): # Login to SE
def getField(field, url="", r=""):
"""gets the hidden field <field> from string <r> ELSE url <url>"""
Expand All @@ -283,7 +283,7 @@ def getField(field, url="", r=""):
self.log("--- NEW LOGIN ---")

email, password = get_credidentials(self.decrypt_key)

# Login to OpenId / CSE
fkey=getField("fkey", "https://openid.stackexchange.com/account/login")
payload = {"email": email, "password": password, "isSignup":"false", "isLogin":"true","isPassword":"false","isAddLogin":"false","hasCaptcha":"false","ssrc":"head","submitButton":"Log in",
Expand All @@ -293,7 +293,7 @@ def getField(field, url="", r=""):
log("Logging to SE - FAILURE - aborting")
abort()
log("Logging to SE - OK")

payload = {"email": email, "password": password, "ssrc":"head", "fkey": fkey}
r = self.sendRequest("https://{}/users/login?ssrc=head&returnurl=https%3a%2f%2f{}%2f".format(host, host),"post",payload).text
if r.find('<a href="https://{}/users/logout"'.format(host))<0:
Expand All @@ -302,10 +302,10 @@ def getField(field, url="", r=""):
log("Loading SE profile - FAILURE - aborting")
abort()
log("Loading SE profile - OK")

# Logs in to all other SE sites
self.sendRequest("https://{}/users/login/universal/request".format(host),"post")

# get chat key
r = self.sendRequest("https://chat.stackexchange.com/chats/join/favorite", "get").text
p=r.find('<a href="/users/')+len('<a href="/users/')
Expand All @@ -314,15 +314,15 @@ def getField(field, url="", r=""):
self.fkey=fkey
log("Got chat fkey : {}".format(fkey))
log("Login to the SE chat successful")

def joinRoom(self,room_id,onActivity): # Join a chatroom
r=Room(room_id, self, onActivity)
self.rooms_joined.append(r)
return r

def leaveAllRooms(self):
for room in self.rooms_joined:
room.leave()

def logout(self):
self.sendRequest('https://openid.stackexchange.com/account/logout', 'post')
self.sendRequest('https://openid.stackexchange.com/account/logout', 'post')

0 comments on commit 77b9134

Please sign in to comment.